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)
 Is this Pivot? Unpivot? or what?

Author  Topic 

Bill_C
Constraint Violating Yak Guru

299 Posts

Posted - 2013-04-10 : 05:16:12
I have a table that I want to copy data from into another table, the table I want to copy data from has data in the form of:-

Field1 | Field2 | Field3 | Field4

d1 | one | T1 | C1
d1 | one | T1 | C2
d1 | one | T1 | C3
d1 | one | T2 | C1
d1 | two | T2 | C2
d1 | two | T2 | C3
d1 | three | T1 | C2
d1 | three | T1 | C3
d2 | one | T1 | C1
d2 | one | T1 | C2
d2 | one | T2 | C1
d2 | one | T2 | C2
d3 | one | T3 | C1
d3 | one | T3 | C2
d3 | one | T3 | C3

I would like to copy over the data to the new table so that it looks like this:-

Field1 | Field2 | Field3 | Field4

d1 | one | T1 | C1,C2,C3
d1 | two | T2 | C2,C3
d1 | three | T1 | C2,C3
d2 | one | T2 | C1,C2
d3 | one | T3 | C1,C2,C3


There are about 800,000 records in the table and Field1, Field2 and Field3 hold many different combinations with lots of entries for Field4 for each (not just the C1,C2,C3 I've used in the example above)

Is there a quicker way of doing this other than using a cursor as the cursor takes a couple of hours to run?

B




Bill_C
Constraint Violating Yak Guru

299 Posts

Posted - 2013-04-10 : 05:24:35
Sorry, had to add pipes to try and break up the field names and data.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-04-10 : 05:31:06
None. its called rowset concatenation

see


SELECT t.*,
STUFF((SELECT ',' + Field4 FROM Table WHERE Field1 = t.Field1 AND Field2 = t.Field2 AND Field3 = t.Field3 ORDER BY Field4 FOR XML PATH('')),1,1,'')
FROM (SELECT DISTINCT Field1,Field2,Field3 FROM Table)t


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Bill_C
Constraint Violating Yak Guru

299 Posts

Posted - 2013-04-10 : 05:47:10
Thank you for your help, that works perfectly.

B
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-04-10 : 05:50:00
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -