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 |
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.