Sum values from multiple rows into one row

前端 未结 2 806
野的像风
野的像风 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条回答
  • 2021-01-11 10:36

    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
    
    0 讨论(0)
  • 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 |
    
    0 讨论(0)
提交回复
热议问题