Postgres:如何聚合一行来报告具有最高值的列名?

时间:2016-02-10 03:26:26

标签: postgresql aggregate-functions

对于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中解决这个问题的正确方法是什么?

1 个答案:

答案 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)