如何获取当月某列的总和?

问题描述 投票:0回答:3

我有一个专栏

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
sql sql-server sql-server-2005
3个回答
1
投票
SQL 服务器 2012+

这应该让你得到你需要的两笔钱,加上一个 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);
SQL Server 2005/2008

看起来我们还没有 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;

0
投票

您的代码中的问题是您是按月或按年而不是两者合计金额。这意味着“本月”的总和正在考虑月份与当前月份相同的所有行,而不考虑年份。类似地,“今年”是对年份与当年相同的所有行求和,而不管月份。

要解决此问题,您需要在条件中同时包含年份和月份。

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

0
投票

您的查询返回 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
匹配时返回)。

© www.soinside.com 2019 - 2024. All rights reserved.