【问题标题】:How to Identify the column with the max value per row如何识别具有每行最大值的列
【发布时间】:2020-09-08 21:12:06
【问题描述】:

我有一个如下所示的表格:

--------------------------------
ENTITY  |  VALUE X  |  VALUE Y  
--------------------------------
AAA     |    100    |    50     
--------------------------------
BBB     |     0     |    20      
--------------------------------
CCC     |    null   |    null   
--------------------------------
DDD     |    100    |    100    
--------------------------------

我想确定哪一列(X 或 Y)具有最大值(在我的实际数据集中有五列,但为了简单起见,我在这里使用两列)。

如果两者都为空,我希望结果为空。

如果出现平局,我想为决胜局设置一个排名 (x > y > z...)

所需的输出如下所示

---------------------------------------------------
ENTITY  |  VALUE X  |  VALUE Y  |  DESIRED OUTPUT  
---------------------------------------------------
AAA     |    100    |    50     |         X        
---------------------------------------------------
BBB     |     0     |    20     |         Y          
---------------------------------------------------
CCC     |    null   |    null   |       null       
---------------------------------------------------
DDD     |    100    |    100    |         X        
---------------------------------------------------

我一直在尝试使用MAX(),但是,我认为这主要是为了比较列中的行,而不是相反...

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: sql oracle plsql subquery unpivot


    【解决方案1】:

    您可以使用case 逻辑来执行此操作。假设没有一个值是NULL

    select t.*,
           (case greatest(x, y)
                when x then 'x'
                when y then 'y'
            end) 
    from t;
    

    【讨论】:

      【解决方案2】:

      如果您有两个以上的列,如问题中所述,那么最具可扩展性的方法使用横向连接。想法是将列转为行,过滤掉null 值,然后按降序排列,只保留最上面的一行:

      select t.*, x.*
      from mytable t
      outer apply (
          select col
          from (
              select 'X' col, t.value_x val from dual
              union all select 'Y', t.value_y from dual
          ) x
          where x.val is not null
          order by x.val desc
          fetch first 1 row only
      ) x
      

      Demo on DB Fiddlde

      实体 | VALUE_X | VALUE_Y |科尔 :----- | ------: | ------: | :--- AAA | 100 | 50 | X 血脑屏障 | 0 | 20 |是 CCC | | | DDD | 100 | 100 | X

      【讨论】:

        猜你喜欢
        • 2017-06-07
        • 2015-04-07
        • 2015-07-07
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多