I have data in one table that contains several rows of data for the same CardNum. I would like to create a table where all the data for the same CardNum is displayed on the same row.
My data is currently like this:
PartID | CardNumber | RdrGrpID | TZID
0 412 31 1
0 412 34 1
0 567 38 1
0 567 33 5
0 567 71 3
This is how I would like the data to be:
PartID | CardNumber | RdrGrpID_1 | TZID_1 | RdrGrpID_2 | TZID_2 | RdrGrpID_3 | TZID_3
0 412 31 1 34 1
0 567 38 1 33 5 71 3
Thank you in advance.
To get this result, there are several ways that you can formulate the query.
If you have a limited number of values for each
partId
andcardNumber
, then you can userow_number()
with an aggregate function/CASE combination:See SQL Fiddle with Demo
You could also use the PIVOT/UNPIVOT function to get the result:
See SQL Fiddle with Demo.
Now if you have an unknown number of values, then you will need to use dynamic sql:
See SQL Fiddle with Demo. All versions gives the result:
I would use PIVOT. Here is an example for the first Id. I would do the same with the second Id and then join the tables.