找到一行中的最大值并使用最大列名称更新新列

时间:2014-09-24 09:23:46

标签: sql sql-server max

我有一张这样的表

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

我该怎么做?

3 个答案:

答案 0 :(得分:2)

<强> QUERY

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)

SQL小提琴

签入SQL Fiddle

模式

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