简体   繁体   中英

How to find the column name of maximum value in a row of table in SQL

Hi i want to find the column name of max vaue of a row in a table

ID       col1  col2  col3
1        15     12    10
2        6      10    3
3        25     50    100
4        150    80    90

Above is my table structure what i need is to find the max value of each row and then find the column name of that max value eg In first row max value is 15 now i want to find that max value of first row is 15 and at the same time i want to find the column name of that max value 15 is col1(15 =>col1)

I need result like below one

ID       Maxval   colname
1        15       col1
2        10       col2    
3        100      col3    
4        150      col1    

After finding the max value and column name i have to insert into another temporary table in the format which is mention above

SELECT ID,
(SELECT MAX(LastUpdateDate)
  FROM (VALUES (col1,col2,col3)) AS UpdateDate(LastUpdateDate)) 
 AS LastUpdateDate
FROM TestTable

This is the sql query i used to find out the max value of each row in a table but i donno how to find the column name of max value in each row after that only i can able to insert into temp table. Please any one understand my issue and help me to resolve this .Thanks

In SQL Server, you can use apply :

select t.*, v.*
from t cross apply
     (select top (1) v.*
      from (values ('col1', col1), ('col2', col2), ('col3', col3)) v(colname, val)
      order by val desc
     ) v

You can use IIF fuinction . The IIF() function returns a value if a condition is TRUE, or another value if a condition is FALSE:

    select ID, 
IIF(col1>col2 and col1>col3,col1,IIF(col2>col1 and col2>col3,col2,col3))max_val,
IIF(col1>col2 and col1>col3,'col1',IIF(col2>col1 and col2>col3,'col2','col3'))col_nam
      from TestTable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM