/****** Скрипт для команды SelectTopNRows из среды SSMS  ******/


insert into [GranPharma].[dbo].[_segmentation] 
SELECT 
      [posName] as Shop
	  ,t4.[contactAltKey] as client
	  ,Mobile as mobile
	  ,cardNumber as cardnumber
	  ,cardtype 
	  ,convert(DATE, [processDate],0) as datetime
	  ,pl_sendsms
      ,sum([totalsumm] - [discountPerc] - [bonusesUSE]/10) as summ
      ,count(distinct chequealtkey) as countcheque
      ,sum([bonusesACC]) as bonus
      ,sum([bonusesUSE]) as writeoff
  FROM [GranPharma].[dbo].[SalesPos] as t1
  join [GranPharma].[dbo].[Pos]  as t2 on (t1.[posAltKey] = t2.[posAltKey] and [posName] like 'Гран%')
  join [GranPharma].[dbo].[Cards] as t3 on (t1.cardAltKey = t3.cardAltKey)
  join [GranPharma].[dbo].[Contacts] as t4 on (t3.contactAltKey = t4.contactAltKey)
  where [processDate] between DATEADD(day, -2, GETDATE()) and DATEADD(day, -1, GETDATE())
  group by  [posName], t4.[contactAltKey], Mobile, cardNumber, cardtype, pl_sendsms, [processDate]
