如何通过使用最大函数postgresql获得最大值的列名?

时间:2019-05-31 09:48:10

标签: sql postgresql

我的表中有四列,分别是col1,col2,col3,col4。 我可以通过使用

找到最大的价值
select greatest(col1,col2,col3,col4) from mytable;

但是我需要知道最大值的列名。

4 个答案:

答案 0 :(得分:0)

使用CASE

select 
  case greatest(col1,col2,col3,col4) 
    when col1 then 'col1'
    when col2 then 'col2'
    when col3 then 'col3'
    when col4 then 'col4'
    else null
  end greatestcolumnname
from mytable;

答案 1 :(得分:0)

您可以使用;

 select case greatest(col1, col2, col3, col4)
          when col1 then
           'col1' || '=' || col1
          when col2 then
           'col2' || '=' || col2
          when col3 then
           'col3' || '=' || col3
          when col4 then
           'col4' || '=' || col4
        end as greatest_value
   from (select max(col1) as col1,
                max(col2) as col2,
                max(col3) as col3,
                max(col4) as col4
           from mytable)

答案 2 :(得分:0)

You can use a lateral join:

select v.*
from t join lateral
     (select v.*
      from (values (col1, 'col1'), (col2, 'col2), (col3, 'col3'), (col4, 'col4)
           ) v(val, colname)
      order by col desc
      fetch first 1 row only
     ) v;

The fact that you want to do this suggests that you have a problem with your data model. You probably want another table, with each column value in a row.

答案 3 :(得分:0)

其他答案很好,我绝对同意Gordon的观点,即闻到数据模型问题。但是,如果表中有唯一键,则可以(ab)使用jsonb来执行此操作,而不必重新输入所有列的名称。

String

基本上,为每一行创建jsonb,类似于create table test (id int, col1 int, col2 int, col3 int); insert into test values (1, 1, 2, 3), (2, 6, 5, 4), (3, 7, 9, 8); select distinct on (id) id, col, val from ( select id, col, val from test join lateral to_jsonb(test) s1(js) on true join lateral jsonb_each(js) s2(col, val) on true ) sub where col != 'id' order by id, val desc; id | col | val ----+------+----- 1 | col3 | 3 2 | col1 | 6 3 | col2 | 9 (3 rows) ,然后使用jsonb_each将其拆分为键和值。结果将是这样的:

{"id": 1, "col1": 1, "col2": 2, "col3": 3}

从此处删除id行,并使用与众不同的on查找每个id的最大val。

您可以在任何表上使用相同的技术,只要不是id,只需更改id列的名称即可。这是另一个示例:

 id | col  | val
----+------+-----
  1 | id   | 1
  1 | col1 | 1
  1 | col2 | 2
  1 | col3 | 3
  2 | id   | 2
  2 | col1 | 6
  2 | col2 | 5
  2 | col3 | 4
...