/****** 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 as 'C'
  FROM [HF_PSA_DB].[dbo].[psa_cheque] as t1 
  left join 
	(select [chequeAltKey], sum(value) as 'D' 
	from [HF_PSA_DB].[dbo].[psa_bonuses]
	where operationTypeID = 'D' and campaignAltKey = 18
	group by [chequeAltKey]) as t2 on t2.chequeAltKey = t1.chequeAltKey
  left join 
	(select [chequeAltKey], sum(value) as 'C' 
	from [HF_PSA_DB].[dbo].[psa_bonuses]
	where operationTypeID = 'C' and campaignAltKey = 18
	group by [chequeAltKey]) as t3 on t3.chequeAltKey = t1.chequeAltKey

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


