我有一个专栏
Amount
,我想在每年内按月获得它的总和。
我已经尝试了以下查询并且它适用于年份但月份总结不正确。比如今年5月份,就是对各个年份的5月份进行汇总。所以我希望它一次对当前的每个月求和。
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
这应该让你得到你需要的两笔钱,加上一个 where 子句,从不包括当年以外的任何金额:
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(Amount) AS [This Year]
FROM Orders
WHERE
[Date] >= DATETIMEFROMPARTS(YEAR(GETDATE()), 1, 1, 0, 0, 0, 0)
AND [Date] < DATETIMEFROMPARTS(YEAR(GETDATE()) + 1, 1, 1, 0, 0, 0, 0);
看起来我们还没有 DateTimeFromParts 所以这里有一个替代方案:
DECLARE @currentYear INT;
DECLARE @currentMonth INT;
DECLARE @YearStart DATETIME;
DECLARE @YearEndExclusive DATETIME;
SELECT @currentYear = DATEPART(YEAR, GETDATE());
SELECT @currentMonth = DATEPART(MONTH, GETDATE());
SELECT @YearStart = CAST(CAST(@currentYear AS VARCHAR(4)) + '0101' AS DATETIME);
SELECT @YearEndExclusive = CAST(CAST(@currentYear + 1 AS VARCHAR(4)) + '0101' AS DATETIME);
SELECT
SUM(CASE WHEN DATEPART(MONTH, [Date]) = @currentMonth THEN Amount ELSE 0 END) AS [This Month],
SUM(Amount) AS [This Year]
FROM Orders
WHERE
[Date] >= @YearStart
AND [Date] < @YearEndExclusive;
您的代码中的问题是您是按月或按年而不是两者合计金额。这意味着“本月”的总和正在考虑月份与当前月份相同的所有行,而不考虑年份。类似地,“今年”是对年份与当年相同的所有行求和,而不管月份。
要解决此问题,您需要在条件中同时包含年份和月份。
DECLARE @currentYear int
DECLARE @currentMonth int
SELECT @currentYear = DATEPART(year, GETDATE())
SELECT @currentMonth = DATEPART(month, GETDATE())
SELECT
SUM(
CASE
WHEN DATEPART(year,[Date]) = @currentYear AND 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
您的查询返回 all 年当月的总数。
在
WHERE
子句中添加关于年份的条件,然后将年份总数简化为 SUM(Amount()
:
SELECT
SUM(CASE WHEN DATEPART(month,[Date]) = @currentMonth THEN Amount END) AS 'This Month',
SUM(Amount) AS 'This Year'
FROM Orders
WHERE DATEPART(year,[Date]) = @currentYear
另外,请注意,您不需要
ELSE
中的CASE
,因为SUM()
忽略空值(当没有CASE
匹配时返回)。