从每个组中选择1行匹配或回退

时间:2018-05-24 08:51:19

标签: sql postgresql select

使用PostgreSQL 9.6,如何从这样的数据中获取:

group | foo | value
------+-----+------
1     | A   | a
1     | B   | b
1     | C   | c
2     | B   | b2
2     | A   | a2
3     | B   | b3
3     | C   | c3

group一行,以便:

  • 如果有foo = A行,请接受
  • 否则从该组获取任何一行?

示例输出:

group | foo | value
------+-----+------
1     | A   | a
2     | A   | a2
3     | B   | b3 <- chosen one row from group 3

3 个答案:

答案 0 :(得分:3)

t=# select distinct on ("group") "group", foo, value 
from table
order by "group", foo = 'A' DESC;
 group  |  foo  | value
--------+-------+-------
 1      |  A    |  a
 2      |  B    |  b2
 3      |  B    |  b3
(3 rows)

我认为neatest将是DISTINCT ON

答案 1 :(得分:1)

试试这个:

SELECT "group", "foo", "value"
FROM (
SELECT "group", "foo", "value",
       ROW_NUMBER() OVER (PARTITION BY "group" 
                          ORDER BY CASE 
                                      WHEN "foo" = 'A' THEN 1
                                      ELSE 2
                                   END, "foo") AS seq
FROM Table1) AS t
WHERE t.seq = 1

查询使用带有条件ROW_NUMBER子句的ORDER BY,以便将'A'条记录优先于其余记录。

Demo here

答案 2 :(得分:0)

以下似乎对我有用:

hidden.component.ts

如果我需要指定选择回退行的标准,我可以通过扩展SELECT DISTINCT group, first_value(foo) OVER (PARTITION BY group ORDER BY foo = 'A' DESC) 'foo', first_value(value) OVER (PARTITION BY group ORDER BY foo = 'A' DESC) 'value' FROM ... 子句来实现,例如。 ORDER BY