My code is producing current year's rows instead of previous year's rows in the last year column
DECLARE @prevYear int
DECLARE @prevMonth int
SELECT @prevYear = DATEPART(year, GETDATE() - 1)
SELECT @prevMonth = DATEPART(month, GETDATE() - 30)
SELECT
SUM(CASE
WHEN DATEPART(month, [OrderDate]) = @prevMonth
THEN Amount
ELSE 0
END) AS 'LastMonth',
SUM(Amount) AS 'LastYear'
FROM
Orders
INNER JOIN
OrderDetail ON Orders.OrderID = OrderDetail.OrderID
WHERE
DATEPART(year, [OrderDate]) = @prevYear
I'm expecting to get previous year (2022) row in last year column
1条答案
按热度按时间aurhwmvo1#
You would be far better off working out the year and then using
DATEFROMPARTS
for a SARGable clause:All column qualifiers are assumed.