选择查询和具有结果的相同查询

时间:2016-07-14 23:30:01

标签: sql postgresql postgresql-9.3

我遇到了一些"复杂的"查询,如:

with q1 as (
select w.entity_id, p.actionable_group, p.error_type
 from issue_analysis p
 join log l on p.id = l.issue_analysis_id
 join website w on l.website_id = w.id
 where l.date >= '2016-06-01'
 group by 1, 2, 3
),
q2 as (
select w.entity_id, p.actionable_group, p.error_type
 from issue_analysis p
 join log l on p.id = l.issue_analysis_id
 join website w on l.website_id = w.id
 where l.date >= '2016-06-01'
 group by 1, 2, 3
 having count(1) = 1
)

试图

SELECT q1.entity_id, count(q1.entity_id), count(q2.entity_id)
from q1, q2
group by 1
order by 1

但是结果为我提供了一个"错误"数据,因为它并不真正包含两个计数...

你可以请描述一下最清洁的"在没有大量嵌套查询的情况下解决此类问题的方法?

如果它可能会有所帮助 - q2q1类似,但最后与having count(1) = 1相似。

P.S。 文档链接会很好,答案很简单。

1 个答案:

答案 0 :(得分:0)

毫无疑问,您获得笛卡尔积,这会影响聚合。相反,在进行连接之前聚合

select q1.entity_id, q1_cnt, q2_cnt
from (select q1.entity_id, count(*) as q1_cnt
      from q1
      group by q1.entity_id
     ) q1 join
     (select q2.entity_id, count(*) as q2_cnt
      from q2
      group by q2.entity_id
     ) q2
     on q1.entity_id = q2.entity_id;