Sum values from multiple rows into one row

梦想与她 提交于 2019-12-03 23:51:33

问题


In SQL Server 2012, I have a table my_table that has columns state, month, ID, and sales.

My goal is to merge different rows that have the same state, month, ID into one row while summing the sales column of these selected rows into the merged row.

For example:

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

This what I am supposed to get

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

I did some research, and I found that the self join is supposed to do something similar to what I am supposed to get.


回答1:


Unless I am missing something in the requirements, why not just use an aggregate function with a GROUP BY:

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

See SQL Fiddle with Demo

The result is:

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



回答2:


Considering there should be an index on column id, this query would be a better solution:

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


来源:https://stackoverflow.com/questions/13940397/sum-values-from-multiple-rows-into-one-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!