查询分组top n是比较常见的需求。而查询的字段又必须在group by 中。当查询字段和groupby 字段不一致的时候,语句就难写了。
select * from tab where id in (
select unnest((array_agg(id))[0:n]) from tab group by groupfield
)
array_agg:聚会转数组
再取n条
unnest:再数组行转列
查询分组top n是比较常见的需求。而查询的字段又必须在group by 中。当查询字段和groupby 字段不一致的时候,语句就难写了。
select * from tab where id in (
select unnest((array_agg(id))[0:n]) from tab group by groupfield
)
array_agg:聚会转数组
再取n条
unnest:再数组行转列