我有以下查询:
SELECT s.id,
s.name,
s.prom,
s.some_other_field,
... many more fields also
FROM mytable s
INNER JOIN (on some other tables etc.)
如果有超过6条记录具有相同的名称(s.name),我想将这些项目组合成一行(我不关心其他哪些数据是分组到该行,即该组的第一个记录就可以了。)
Postgres有可能吗?我想这是一个条件组,从某种意义上说,我想将同名出现超过6次的记录分组,同时正常返回所有其他记录。
非常感谢任何帮助 - 谢谢!
答案 0 :(得分:6)
你可以这样做:
select * from (
SELECT s.id,
s.name,
s.prom,
s.some_other_field,
... many more fields also,
row_number() over (partition by s.name order by s.id) as rnk,
count(*) over (partition by s.name) cnt
FROM mytable s
INNER JOIN (on some other tables etc.)
) a
where cnt < 6 or (cnt >=6 and rnk = 1)