I have a column Amount which I want to get its sum by month within each year.
I have tried the following query and it works well for year but month is summing up incorrectly. For instance in this May, it's summing up all the month of May in various years. So I want it to sum each current month at a time.
DECLARE @currentYear int
DECLARE @currentMonth int
SELECT @currentYear = DATEPART(year, GETDATE())
SELECT @currentMonth = DATEPART(month, GETDATE())
SELECT
SUM(
CASE
WHEN DATEPART(month,[Date]) = @currentMonth THEN Amount
ELSE 0
END
) AS 'This Month',
SUM(
CASE
WHEN DATEPART(year,[Date]) = @currentYear THEN Amount
ELSE 0
END
) AS 'This Year'
FROM Orders
SQL SERVER 2012+
This should get you the two sums you need, with a where clause added to never include any amounts outside of the current year:
Sql Server 2005/2008
It looks like we don't have DateTimeFromParts yet so here's an alternative: