2012-12-18 42 views
13

在SQL Server 2012中,我有一個表my_table,其列state, month, IDsales將多行中的總和值合併爲一行

我的目標是將具有相同state, month, ID的不同行合併到一行中,同時將這些選定行的sales列合計到合併行中。

例如:

state month ID sales 
------------------------------- 
FL  June  0001 12,000 
FL  June  0001 6,000 
FL  June  0001 3,000 
FL  July  0001 6,000 
FL  July  0001 4,000 
TX  January 0050 1,000 
MI  April 0032 5,000 
MI  April 0032 8,000 
CA  April 0032 2,000 

這就是我應該得到

state month ID sales 
------------------------------- 
FL  June  0001 21,000 
FL  July  0001 10,000 
TX  January 0050 1,000 
MI  April 0032 13,000 
CA  April 0032 2,000 

我做了一些研究,我發現,自聯接應該做同樣的事情對我是什麼應該得到。

+4

SUM()的[documentation](http://msdn.microsoft.com/en-us/library/ms187810.aspx)有一些清晰的例子 – Pondlife

回答

16

除非我缺少的需求的東西,爲什麼不使用聚合函數與GROUP BY

select state, month, id, sum(sales) Total 
from yourtable 
group by state, month, id 
order by id 

SQL Fiddle with Demo

結果是:

| STATE | MONTH | ID | TOTAL | 
-------------------------------- 
| FL | July | 1 | 10000 | 
| FL | June | 1 | 21000 | 
| CA | April | 32 | 2000 | 
| MI | April | 32 | 13000 | 
| TX | January | 50 | 1000 | 
3

考慮有應該是列id上的索引,該查詢將是更好的解決方案:

select state, month, id, sum(sales) Total 
from yourtable 
group by id, state, month 
order by id