/****** Script for SelectTopNRows command from SSMS  ******/
declare @date1 date;
declare @date2 date;
set @date1 = '2023-03-01'; -- начало
set @date2 = '2023-04-08'; -- конец
SELECT t1.[chequeAltKey]
      ,cast([processDate] as date) as 'date'
      ,[contactAltKey]
      ,[chequePriceSum]
      ,[chequeDiscount]
      ,[chequeSumWDisc]
      ,[loyaltySale]
      ,[bonusesAcc]
      ,[bonusesUsed]
	  ,D,
	  'C'= case
	   when C >= 500 then 500
	   when C < 500 then C
	   end
  FROM [NAS_TR_Base1].[dbo].[psa_cheque] as t1 
  left join 
	(select [chequeAltKey], sum(value) as 'D' 
	from [NAS_TR_Base1].[dbo].[psa_bonuses]
	where operationTypeID = 'D' and campaignAltKey =86
	group by [chequeAltKey]) as t2 on t2.chequeAltKey = t1.chequeAltKey
  left join 
	(select [chequeAltKey], sum(value) as 'C' 
	from [NAS_TR_Base1].[dbo].[psa_bonuses]
	where operationTypeID = 'C' and campaignAltKey = 86
	group by [chequeAltKey]) as t3 on t3.chequeAltKey = t1.chequeAltKey

  where [processDate] between @date1 and @date2 and
  contactAltKey in (Select [CardOwnerAltKey] from
  [NAS_Sales_DW1].[dbo].[CardOwnersMarketGroupsMeasure]
  where [CardOwnersMarketGroupName] in ('2023.03 Бонусы к ДР (подарок 500ББ)_АП Доставлено СМС 1','КГ_2023.03 Бонусы к ДР (подарок 500ББ)_АП'))
  order by processDate

