SQL Server 2008中按季度和月份分组

时间:2012-03-03 14:54:09

标签: sql sql-server sql-server-2008 tsql

我知道SQL专家的常见问题将能够提供帮助。说我有一张这样的桌子:

Quarter  | Month  |  Group  |  Member  |  Value
Q1 2011  | Jan    |  10     |  343     | 10
Q1 2011  | Jan    |  1      |  3       | 10
Q1 2011  | Jan    |  4      |  6       | 10
Q1 2011  | Feb    |  34     |  33      | 10
Q1 2011  | Feb    |  5      |  6       | 10
Q1 2011  | Mar    |  54     |  33      | 10
Q2 2011  | Apr    |  76     |  33      | 10
Q2 2011  | May    |  98     |  33      | 10
Q2 2011  | May    |  9      |  1       | 10
...

我想分组,以便我将这些月份和季度汇总在一起,现在就是:

Quarter  | Month  |  Group  |  Member  |  Value
Q1 2011  | Jan    |  15     |  352     | 30
Q1 2011  | Feb    |  39     |  39      | 20
...

帮助!

1 个答案:

答案 0 :(得分:3)

直接使用GROUP BY子句对您有用:

SELECT [Quarter], [Month], SUM([Group]) as [Group], SUM([Member]) as Member, 
  SUM([Value]) as [Value]
FROM dbo.YourTableName
GROUP BY [Quarter], [Month]