postgresql:如何从group by子句中获取主键?

Cla*_*diu 7 sql postgresql group-by

这是一个选择一组所需行的查询:

select max(a), b, c, d, e
from T
group by b, c, d, e;
Run Code Online (Sandbox Code Playgroud)

该表在列中有一个主键id.

我想通过从每个行中获取主键来在另一个查询中标识这些行.我该怎么办?这不起作用:

select id, max(a), b, c, d, e
from T 
group by b, c, d, e;

ERROR:  column "T.id" must appear in the GROUP BY clause or be used in an aggregate function
Run Code Online (Sandbox Code Playgroud)

我在其他一些postgresql问题中尝试了这个,但没有运气:

select distinct on (id) id, max(a), b, c, d, e
from T 
group by b, c, d, e;

ERROR:  column "T.id" must appear in the GROUP BY clause or be used in an aggregate function
Run Code Online (Sandbox Code Playgroud)

我该怎么办?我知道id每个结果只能有一个,因为它是一个主键...我真的希望主键和其余数据,对于初始(工作)查询返回的每一行.

mu *_*ort 5

如果你不关心id你得到了什么,那么你只需要包含id一些保证给你有效的聚合函数id.我想到了这些maxmin聚合:

-- Or min(id) if you want better spiritual balance.
select max(id), max(a), b, c, d, e
from T 
group by b, c, d, e;
Run Code Online (Sandbox Code Playgroud)

根据你的数据,我认为使用窗口函数将是一个更好的计划(感谢恶魔otto引导到头部):

select id, a, b, c, d, e
from (
    select id, a, b, c, d, e, rank() over (partition by b,c,d,e order by a desc) as r
    from T
) as dt
where r = 1
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此查询返回的行不一定是表中的行. (2认同)