繁体   English   中英

在一行中找到最大值,并使用最大列名更新新列

[英]find max value in a row and update new column with the max column name

我有这样的桌子

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

我怎样才能做到这一点?

QUERY

SELECT *,(
SELECT MAX(n) 
    FROM
    (
        VALUES(col1),(col2),(col3),(col4)
    ) AS t(n)
)  AS maximum_value
FROM #tmp

更新声明

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];

假设数字是关键列

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM