[英]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.