I have a one to many mapping table displayed as below. I need to display the ICD10
HORIZONTALLY.
for each ICD9
. The data is dynamic hence I cannot use the static pivot function.
ICD9 | ICD10
-----+------
0156 | 0178
0156 | 0179
0123 | 0181
0152 | 0202
0231 | 0210
0231 | 0211
0231 | 0212
I want the result to be displayed as-
ICD9 | ICD10 | ICD10 | ICD10
0156 | 0178 | 0179 | null
0123 | 0181 | null | null
0152 | 0202 | null | null
0231 | 0210 | 0211 | 0212
Currently I tried to use this code:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(icd10)
FROM mv_icd
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT icd9, ' + @cols + ' from
(
select icd9,icd10 from mv_icd
) x
pivot
(
min(icd9)
for icd10 in (' + @cols + ')
) p '
execute(@query)
but it does not work as I have too many records (about 12000). How can I alter the code to display the ICD10
for each ICD9
in a column?
icd10
that you will have for eachicd9
?