SQLTeam.com | Weblogs | Forums

Get the column name from specific value

sql2012
sql2008
sql2014
sql2008r2

#1

Hi ,

I have this table -

create table t(id int , x1 int,x2 int,x3 int ,x4 int ,x5 int );

insert into t select 5555,4,3,5,2,1

i was able to take the minimum value for id 5555 which is 1 , but i also need to take the column name for this values - means x5 .

How can i do it ?


#2
SELECT ca1.*
FROM t
CROSS APPLY (
    SELECT TOP (1) *
    FROM (VALUES('x1',x1),('x2',x2),('x3',x3),
        ('x4',x4),('x5',x5)) AS t_values(column_name, value)
    ORDER BY value, column_name
) AS ca1