简体   繁体   中英

Column name with max value in SQL

I have the below sample dataset:

在此处输入图像描述

I want to get the name of the column that has the maximum value, in this case 'C'. MAX doesn't return the desired result as it cant be used with multiple columns.

SELECT MAX(A,B,C,D)
FROM TABLE

Could someone pls help.

One possible approach is the following statement, using VALUES table value constructor:

Table:

CREATE TABLE Data (A int, B int, C int, D int)
INSERT INTO Data (A, B, C, D) VALUES (50, 100, 400, 200)

Statement:

SELECT d.*, c.*
FROM Data d
CROSS APPLY (
   SELECT TOP 1 v.ColumnName, v.ColumnValue
   FROM (VALUES 
      ('A', d.A), 
      ('B', d.B), 
      ('C', d.C), 
      ('D', d.D)
   ) v (ColumnName, ColumnValue)
   ORDER BY v.ColumnValue DESC
) c

Result:

A   B   C   D   ColumnName  ColumnValue
50  100 400 200 C           400

If the table has multiple max values in one row, you may use the following statement:

SELECT d.*, c.*
FROM Data d
CROSS APPLY (
   SELECT v.ColumnName, v.ColumnValue, DENSE_RANK() OVER (ORDER BY v.ColumnValue DESC) AS RN
   FROM (VALUES 
      ('A', d.A), 
      ('B', d.B), 
      ('C', d.C), 
      ('D', d.D)
   ) v (ColumnName, ColumnValue)
) c
WHERE c.RN = 1

One way to do it is with union and max:

with cte as( select a as col, 'A' col_name
             from Data
             union 
             select b, 'B' col_name
             from Data
             union
             select c, 'C' col_name
             from Data
             union
             select d, 'D' col_name
             from Data
) select * 
  from cte
  where col = (select max(col) 
               from cte);

Result:

| col | col_name |
+-----+----------+
| 400 |    C     |

Here is a demo

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