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