Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Merge several rows to one row

Author  Topic 

msallem
Starting Member

2 Posts

Posted - 2012-12-18 : 15:33:40
In SQL 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 and 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. Any help would be greatly appreciated. Thank you!

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2012-12-18 : 15:44:28
Just group by state,month and ID and do SUM of sales.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-12-19 : 00:57:26
No need to join. Read about GROUP BY in BOL as Sodeep suggested

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

msallem
Starting Member

2 Posts

Posted - 2012-12-19 : 13:49:11
Thank you!
Go to Top of Page
   

- Advertisement -