我有一张这样的表
number col1 col2 col3 col4 max
---------------------------------------
0 200 150 300 80
16 68 250 null 55
我想在每一行中找到col1,col2,col3,col4之间的最大值,并用最大值列名更新最后一列“max”!
例如在第一行中最大值为300,“max”列值将为“col3” 结果如下:
number col1 col2 col3 col4 max
------------------------------------------
0 200 150 300 80 col3
16 68 250 null 55 col2
我该怎么做?
答案 0 :(得分:2)
SELECT *,(
SELECT MAX(n)
FROM
(
VALUES(col1),(col2),(col3),(col4)
) AS t(n)
) AS maximum_value
FROM #tmp
答案 1 :(得分:0)
更新声明
with MaxValues
as (select [number], [max] = (
select (
select max ([n])
from (values ([col1]) , ([col2]) , ([col3]) , ([col4])) as [t] ([n])
) as [maximum_value])
from [#tmpTable])
update [#tmpTable]
set [max] = [mv].[max]
from [MaxValues] [mv]
join [#tmpTable] on [mv].[number] = [#tmpTable].[number];
假设 number 是一个关键列
答案 2 :(得分:0)
DECLARE @temp table ([number] int NOT NULL, [col1] int, [col2] int, [col3] int, [col4] int, [colmax] int);
INSERT @temp VALUES (0, 200, 150, 300, 80, null), (16, 68, 250, null, 55, null);
SELECT number
,(
SELECT MAX(col) maxCol
FROM (
SELECT t.col1 AS col
UNION
SELECT t.col2
UNION
SELECT t.col3
UNION
SELECT t.col4
) a
) col
FROM @temp t
,更新声明是 -
UPDATE tempCol
SET colmax = a.col
FROM (
SELECT (
SELECT MAX(col) maxCol
FROM (
SELECT t.col1 AS col
UNION
SELECT t.col2
UNION
SELECT t.col3
UNION
SELECT t.col4
) a
) col
FROM tempCol t
) a