0

我有以下查询,它显示如下数据:

Income Type This Month  Last Month  This Year   Last Year
1           179640.00   179640.00   179640.00   179640.00
2           12424440.00 12424440.00 12424440.00 12424440.00


Select
  Income_Type As [Income Type],
  Sum(Income_Amount) As [This Month],
  Sum(Income_Amount) As [Last Month],
  Sum(Income_Amount) As [This Year],
  Sum(Income_Amount) As [Last Year]
From Income I
Left Join Finance_Types FT On I.Income_Type = FT.Type_ID
Group By
Income_Type

收入表有一个收入日期,它是一个日期时间列。

如果可能的话,我正在努力弄清楚如何在一个查询中使用正确的总和提取“本月”、“上个月”、“今年”、“去年”的数据?

4

1 回答 1

2

使用日期函数:

SUM(CASE WHEN YEAR(yourdatefield) = YEAR(GetDate()) - 1 THEN Income_Amount ELSE 0 END) AS 'Last Year'

如果是最后一年,该案例语句仅返回 Income_Amount,因此您将仅汇总这些金额。

如果您不使用 SQL Server,则语法可能会有所不同。

于 2012-11-15T21:31:37.557 回答