在收入数据上显示不同的日期

时间:2012-11-15 21:26:51

标签: sql

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

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

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

如果可能的话,我很难理解如何在一个查询中提取“本月”,“上个月”,“今年”,“去年”以及正确的总和数据? / p>

1 个答案:

答案 0 :(得分:2)

使用日期功能:

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

如果是最后一年,那个案例陈述只返回Income_Amount,所以你只会总结那些金额。

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