簡體   English   中英

如何使用最大函數postgresql獲取最大值的列名?

[英]how to get the column name of the greatest value by using greatest function postgresql?

我的表中有四列,它們是 col1、col2、col3、col4。 我可以通過使用找到最大的價值

select greatest(col1,col2,col3,col4) from mytable;

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

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;

其他答案都很好,我絕對同意 Gordon 的觀點,即這有數據模型問題的味道。 但是,如果您的表中有唯一鍵,您可以(ab)使用 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,類似於{"id": 1, "col1": 1, "col2": 2, "col3": 3} ,然后使用 jsonb_each 將其拆分為鍵和值。 結果將是這樣的:

 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
...

從那里,刪除 id 行並使用 distinct on 找到每個 id 的最大 val。

您可以在任何表上使用相同的技術,您只需更改 id 列的名稱,如果它不是 id。 這是另一個例子:

create table test2 (id int, t1 timestamp, t2 timestamp);
insert into test2 values (1, '2019-02-01T00:00:00', '2019-01-01T00:00:00');

select distinct on (id)
  id,
  col,
  val
from (
    select id,
           col,
           val
    from test2
    join lateral to_jsonb(test2) 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 | t1  | "2019-02-01T00:00:00"
(1 row)

您可以使用;

 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)

您可以使用橫向連接:

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;

您想要這樣做的事實表明您的數據模型存在問題。 您可能需要另一個表,其中每一列的值都在一行中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM