【问题标题】:find max value in a row and update new column with the max column name在一行中找到最大值并使用最大列名更新新列
【发布时间】:2014-11-18 17:30:09
【问题描述】:

我有一张这样的桌子

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

我该怎么做?

【问题讨论】:

标签: sql sql-server max


【解决方案1】:

查询

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

【讨论】:

    【解决方案2】:

    更新声明

    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 是一个键列

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多