如何选择满足计数条件的行

时间:2016-12-09 23:57:05

标签: sql oracle11g

我只想展示拥有超过10个地点的公司和地点。

select distinct company_id,
count(distinct location_id) location_id_count
from bigtable
where condition1 = 'x'
group by company_id
having count(distinct location_id) > 10;

这会返回company_id以及公司位置超过10个时的位置数,但我想要查看的是所有位置ID。有没有子查询可以做到这一点?我的查询中有很多条件,在主查询和子查询中的where子句中重复相同的10个条件似乎不是最佳做法。

这是我尝试解决方案,但它运行不正常,因为在使用子查询时,我获得了大约0.005%的额外位置,而不是从主查询中总结location_id_counts

with MainQry as(
select distinct company_id,
count(distinct location_id) location_id_count
from bigtable
where condition1 = 'x'
group by company_id
having count(distinct location_id) > 10
)

select distinct m.company_id,
b.location_id
from MainQry m
join BigTable b
on m.company_id = b.company_id
where b.condition1 = 'x';

0 个答案:

没有答案