CREATE TABLE test_max (
number_a INT,
number_b INT,
number_c INT,
)
GO
INSERT INTO test_max VALUES(3,7,9)
INSERT INTO test_max VALUES(5,2,10)
INSERT INTO test_max VALUES(31,4,91)
INSERT INTO test_max VALUES(35,124,1)
GO
select number_a,number_b,number_c from test_max
我想要打印第四列,即max(number_a.value,number_b.value,number_c.value)
所以输出应该像
3 7 9 9
5 2 10 10
31 4 91 91
35 124 1 124
是否可以不使用PIVOT,因为列可能不仅仅是3?
答案 0 :(得分:1)
您可能希望MAX
中的GREATEST
等行MySQL/Oracle
等效:
SELECT number_a,number_b,number_c, c.s AS greatest
FROM #test_max
CROSS APPLY (SELECT MAX(v)
FROM (VALUES (number_a),(number_b),(number_c)) AS c(v)
) AS c(s)
的 LiveDemo
强>
如果您使用SQL Server 2008
以下的版本,请使用:
SELECT number_a,number_b,number_c, c.s AS greatest
FROM #test_max
CROSS APPLY (SELECT MAX(v)
FROM (SELECT number_a AS v
UNION ALL SELECT number_b
UNION ALL SELECT number_c
) AS c(v)
) AS c(s);
输出:
╔══════════╦══════════╦══════════╦══════════╗
║ number_a ║ number_b ║ number_c ║ Greatest ║
╠══════════╬══════════╬══════════╬══════════╣
║ 3 ║ 7 ║ 9 ║ 9 ║
║ 5 ║ 2 ║ 10 ║ 10 ║
║ 31 ║ 4 ║ 91 ║ 91 ║
║ 35 ║ 124 ║ 1 ║ 124 ║
╚══════════╩══════════╩══════════╩══════════╝
工作原理:
VALUES/UNION ALL
MAX
值Using APPLY