繁体   English   中英

LIMIT 基于 COUNT 的 DISTINCT `foreign_key` 到目前为止

[英]LIMIT based on COUNT of DISTINCT `foreign_key` so far

我有 2 个表“站点”和“卡车”的联合(按distance排序)。 记录集如下所示:

在此处输入图片说明

我需要获取所有行,直到达到特定 (n) 数量的唯一 company_id,从第 1 行开始。

所以,如果我得到如下内容: 在此处输入图片说明

然后我可以做一个简单的查询,例如:

SELECT * FROM union_recordset where distinct_company_id_count_so_far < (3 + 1);
-- where n = 3

并获得所需的结果:

在此处输入图片说明

如果您的数据库支持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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM