SQL server compare multiple columns and display text when two values match -
i have table multiple columns identifying body area injured:
id head face thor abdo spine area injured 4721 5 0 5 3 0 multiple 4723 0 0 0 3 3 multiple 4737 0 0 1 3 0 abdo 4752 0 2 0 0 0 face
at present, [area injured] column based on column contains highest value, if 2 columns have joint highest value, lists 'multiple'.
i want change [area injured] column , list actual body areas instead of 'multiple', example:
id head face thor abdo spine area injured 4721 5 0 5 3 0 head, thor 4723 0 0 0 3 3 abdo, spine 4737 0 0 1 3 0 abdo 4752 0 2 0 0 0 face
how compare 5 columns establish columns have highest values?
one way use case
expressions find columns largest value:
select *, [area injured] = stuff(( case when head >= face , head >= thor , head >= abdo , head >= spine ', head' else '' end + case when face >= head , face >= thor , face >= abdo , face >= spine ', face' else '' end + case when thor >= head , thor >= face , thor >= abdo , thor >= spine ', thor' else '' end + case when abdo >= head , abdo >= face , abdo >= thor , abdo >= spine ', abdo' else '' end + case when spine >= head , spine >= face , spine >= abdo , spine >= thor ', spine' else '' end ), 1, 2, '') tbl
another way, more dynamic, unpivot
data , use rank
column highest value. then, use for xml path('')
concatenation:
with cteunpivot as( select t.id, x.col, x.value tbl t cross apply(values ('head', t.head), ('face', t.face), ('thor', t.thor), ('abdo', t.abdo), ('spine', t.spine) )x(col, value) ), ctern as( select *, rn = rank() over(partition id order value desc) cteunpivot ) select c.id, [area injured] = stuff(( select ', ' + col ctern id = c.id , rn = 1 xml path('') ),1 ,2, '') ctern c group c.id
Comments
Post a Comment