[英]LIMIT based on COUNT of DISTINCT `foreign_key` so far
如果您的数据库支持count(distinct)
作为窗口函数:
select ur.*,
count(distinct company_id) over (order by distance) as cnt
from union_recordset ur
order by distance;
如果没有,您可以计算第一次出现:
select ur.*,
sum(case when seqnum = 1 then 1 else 0 end) over (order by distance) as cnt
from (select ur.*,
row_number() over (partition by company_id order by distance) as seqnum
from union_recordset ur
) ur
order by distance;
在 Postgres 中, sum()
可以简化为:
sum( (seqnum = 1)::int ) over (order by distance) as cnt
然后要获得前三家公司的数字,您需要:
select ur.*
from (select ur.*,
sum( (seqnum = 1)::int ) over (order by distance) as cnt
from (select ur.*,
row_number() over (partition by company_id order by distance) as seqnum
from union_recordset ur
) ur
) ur
where cnt <= 3
order by distance;
您可以选择您的公司,然后将其与自己再次连接以获取其他数据:
select ur.* from union_recordset ur join
(select distinct company_id from union_recordset order by distance limit 3) ur_d
on (ur.company_id = ur_d.company_id)
注意:PostgreSQL 8.1 之后支持Limit
命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.