Одним из способов достижения этой цели является использование CTE, которое рассчитывает доход за предыдущий год на одного клиента, а затем присоединяет его к основному запросу.
declare @InvcStartDate date = '2018-06-30', @InvcEndDate date = '2019-06-30';
declare @ProfitReport table (
CustId int,
CustName nvarchar(15),
InvcDate date,
NetRevenue float,
CustType nvarchar(3)
);
declare @Cust_View table (
CustId int
);
insert @Cust_View
values
(1),
(2),
(3),
(4);
insert @ProfitReport (CustId, CustName, InvcDate, NetRevenue, CustType)
values
(1, 'Bob', '2017-07-01', 500.75, 'Old'),
(2, 'Linda', '2018-02-05', 320.13, 'Old'),
(1, 'Steve', '2018-07-06', 612.04, 'New'),
(2, 'Jane', '2019-05-18', 130.00, 'Old');
with previousyear as ( SELECT
p.CustID as [Cust ID],
p.CustName as [Cust Name],
p.InvcDate as [Invoice Date],
SUM(NetRevenue) as [Net Revenue]
FROM @ProfitReport p
LEFT JOIN @Cust_view v ON p.CustID = v.CustId
WHERE p.InvcDate BETWEEN dateadd(year, -1, @InvcStartDate) AND dateadd(year, -1, @InvcEndDate)
and p.CustType IN ('New','Old')
GROUP BY
p.CustID,
p.CustName,
p.InvcDate)
SELECT
p.CustID as [Cust ID],
p.CustName as [Cust Name],
p.InvcDate as [Invoice Date],
SUM(p.NetRevenue) as [Net Revenue],
p2.[Net Revenue] as [Prior Net Revenue]
FROM @ProfitReport p
LEFT JOIN @Cust_view v ON p.CustID = v.CustId
left join previousyear p2 on p.CustId=p2.[Cust ID]
WHERE p.InvcDate BETWEEN @InvcStartDate AND @InvcEndDate
and p.CustType IN ('New','Old')
GROUP BY
p.CustID,
p.CustName,
p.InvcDate,
p2.[Net Revenue];