简体   繁体   中英

Group By Quarter and Month in SQL Server 2008

Common problem which I know the SQL gurus out there will be able to help. Say I have a table like so:

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
...

I want to group by so that I get the months and quarters summed together so that it is now:

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

Help!

A straightforward use of the GROUP BY clause will work for you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM