对于postgres表中的每一行,我正在尝试确定具有最高值的列的名称:
输入
row_id | type1 | type2 | type3
--------+-------+-------+-------
A | 2 | 44 | 7
B | 321 | 5 | 73
C | 302 | 620 | 9
所需的输出
row_id | max_type | max_value
--------+----------+-----------
A | type2 | 44
B | type1 | 321
C | type2 | 620
这类似于this SQL Server question,但CROSS APPLY
似乎not be precisely related to anything in postgres。
我试过这个,但是它遍历了整个表格,而不是一次遍历一行:
SELECT
unnest(ARRAY['type1','type2','type3']) AS max_type,
unnest(ARRAY[type1,type2,type3]) AS max_value
FROM table
ORDER BY max_value DESC
LIMIT 1;
在postgres中解决这个问题的正确方法是什么?
答案 0 :(得分:1)
将DISTINCT ON (row_id)
与ORDER BY row_id, max_value DESC
:
SELECT DISTINCT ON (row_id) row_id, max_type, max_value
FROM (
SELECT
row_id,
unnest(ARRAY['type1','type2','type3']) AS max_type,
unnest(ARRAY[type1,type2,type3]) AS max_value
FROM a_table
) s
ORDER BY row_id, max_value DESC;
row_id | max_type | max_value
--------+----------+-----------
A | type2 | 44
B | type1 | 321
C | type2 | 620
(3 rows)