I am using SQL Server 2008 R2 version 10.50.1600.1.
I'm trying to pivot a table with strings but the pivot column shares the same name. This is what my data looks like.
+------------+-----------+------------+ | patient_ID | code_type | code_value | +------------+-----------+------------+ | 1 | ICD9 | V70 | | 1 | ICD9 | 401.9 | | 1 | ICD9 | 616 | | 1 | ICD9 | 338.21 | | 2 | ICD9 | V10 | | 2 | ICD9 | 250 | +------------+-----------+------------+
What I'm trying to get to is this ...
+------------+--------+--------+--------+--------+--------+--------+ | patient_id | ICD9_1 | ICD9_2 | ICD9_3 | ICD9_4 | ICD9_5 | ICD9_x | +------------+--------+--------+--------+--------+--------+--------+ | 1 | V70 | 401.9 | 616 | 338.21 | null | null | | 2 | V10 | 250 | null | null | null | null | +------------+--------+--------+--------+--------+--------+--------+
ICD9_x can stretch to infinity because I don't know how many ICD9 codes there will be for a given patient.
Is there a way to do this in SQL?
Thanks!
Update:
Thanks for all the help! I have received two errors. It looks like pivoting requires the values to be an int because of the sum right? Is there a way to use the pivot table for string values? The ICD9 codes are all strings.
Secondly, I hit an unexpected error. It says that "the number of elements in the select list exceeds the maximum allowed number of 4096 elements." Is there a solution for a large data set?
Thanks again!