行记录的最大值为列

时间:2015-11-18 14:46:52

标签: sql sql-server tsql

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?

1 个答案:

答案 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 ║
╚══════════╩══════════╩══════════╩══════════╝

工作原理:

  1. 创建派生表(子查询),其行值为表VALUES/UNION ALL
  2. 从派生表中获取MAX
  3. 为表格中的每一行执行此操作 Using APPLY