Sum values from multiple rows into one row

前端 未结 2 881
野的像风
野的像风 2021-01-11 10:26

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

2条回答
  •  梦毁少年i
    2021-01-11 10:43

    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 |
    

提交回复
热议问题