Wednesday, March 7, 2012

Convert rows to colums

I am getting this from my client
TableA
StorID LineNumber Text
30000 1 ClientName
30000 2 ClientSurname
30000 3 3333333
30000 4 20-05-2004

I actually want this to look like
TableB
StoryID Name Surname Policy Date
30000 Name Surname 3333333 20-05-2004

Can you help with the script to convert this to one record with many fields (as in TableB) if this isyou need a sort of a pivot table where the cross function is the identity function. I've used this code in a project, and it works fine,..though performance are surely not the best. Otherwise you can wait for SQL2005 :-)

some very useful code (very general, you probably should modify it to best suit your db schema) can be found here:

http://www.sqlteam.com/item.asp?ItemID=2955|||create a function (called get_val) with storid, and linenumber as arguements.

in the function:

select <text> from tableA
where storid = <arg1> and linenumber = <arg2>
return <text>

then...to populate table b:

INSERT INTO tableB (storid,name,surname,policy_date)
SELECT DISTINCT storid, get_val(storid,1),get_val(storid,2),get_val(storid ,3),get_val(storid,4) FROM tableA|||I'd suggest using something like:SELECT a.storID
, Min(CASE WHEN 1 = a.LineNumber THEN a.[Text]) AS [Name]
, Min(CASE WHEN 2 = a.LineNumber THEN a.[Text]) AS [Surname]
, Min(CASE WHEN 3 = a.LineNumber THEN a.[Text]) AS [Policy]
, Min(CASE WHEN 4 = a.LineNumber THEN a.[Text]) AS [Date]
FROM TableA AS a
GROUP BY a.StorID-PatP|||much better....nice pat.

No comments:

Post a Comment