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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Group multiple rows into one

Author  Topic 

kevin0983
Starting Member

2 Posts

Posted - 2012-06-20 : 03:55:24
Hi, I need help in creating a query to group identical rows into one and placing corresponding data in appropriate columns, what I mean is that I have a table structured as below

Itemcode, Description, Period1, Period2, Period3
001 Desc 233,0,0
001 Desc 0,100,0
001 Desc 0,0,300

I need to create a query so that the end result would look like this;

Itemcode, Description, Period1, Period2, Period3
001 Desc 233 100 300

Can you please help / guide in creating an sql query to get the above result?

Thanks

Kevin

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2012-06-20 : 04:06:47
Are the 3 entries in period1?
If so
update tbl
set period3 = right(Period1,charindex(',',reverse(Period1))-1),
period1 = left(Period1,len(period1-charindex(',',reverse(Period1)))

update tbl
set period2 = right(Period1,charindex(',',reverse(Period1))-1),
period1 = left(Period1,len(period1-charindex(',',reverse(Period1)))

It can be done in a single query but this is probably easiest.
There are probably a couple of mistakes in the above but you'll get the idea.

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

kevin0983
Starting Member

2 Posts

Posted - 2012-06-20 : 04:20:38
Hi Nigel, thanks for your reply.

No all entries are in different peroiods that's why I placed the 0. I have an entry for item 001 in period 1 another entry for period 2 and so on.

Thanks,
Go to Top of Page
   

- Advertisement -