我有一个包含ID,A,B,C,D,E ......列的表格(总共10个数字列)
对于每一行,我需要找到哪个列具有最大值,以及该值是什么。
E.G。这是我桌子的一排:
ID A B C D E F G H I J
XY 5 4 9 5 0 1 3 2 1 7
我想生成2个新列:
maxvalue,等于9,和
maxcol,等于“C”
除了大量的IF声明之外还有什么建议?
答案 0 :(得分:1)
我没有可用的sql处理器,但是
的内容select id , colName
from
(select id, 'A' as colName, a as value union all
select id, 'B' as colName, b as value union all
select id, 'C' as colName, c as value union all
select id, 'D' as colName, d as value union all
select id, 'E' as colName, e as value union all
select id, 'F' as colName, f as value union all
select id, 'G' as colName, g as value union all
select id, 'H' as colName, h as value union all
select id, 'I' as colName, i as value union all
select id, 'J' as colName, j as value)
group by id having max(value)
答案 1 :(得分:0)
使用unpivot
的解决方案,假设您的表名为“TestTable”:
WITH unpivoted as
(
SELECT * FROM TestTable
UNPIVOT
(
Val FOR Col IN (A, B, C, D, E, F, G, H, I, J)
) as u
),
maxvals as (
SELECT ID, max(val) as MaxVal
FROM unpivoted
GROUP BY ID
)
SELECT
TestTable.*,
MaxVals.MaxVal,
(SELECT top 1 Col
FROM unpivoted
WHERE unpivoted.Id = TestTable.ID and Val = MaxVals.MaxVal) as MaxCol
FROM
TestTable
JOIN maxvals on maxvals.id = TestTable.Id