[英]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'.我想获取具有最大值的列的名称,在本例中为“C”。
MAX
doesn't return the desired result as it cant be used with multiple columns. MAX
不会返回所需的结果,因为它不能与多列一起使用。
SELECT MAX(A,B,C,D)
FROM TABLE
Could someone pls help.有人可以帮忙吗。
One possible approach is the following statement, using VALUES
table value constructor:一种可能的方法是使用
VALUES
表值构造函数的以下语句:
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:如果表格在一行中有多个
max
,您可以使用以下语句:
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:一种方法是使用 union 和 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 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.