select 查询和具有结果的相同查询
select query and same query with having results
我遇到了一些 "complicated" 查询,例如:
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
但结果为我提供了一个 "wrong" 数据,因为它并没有真正包含这两个计数...
您能否描述无需大量嵌套查询即可解决此类问题的最 "cleaner" 方法?
如果它可能有帮助 - q2
类似于 q1
但在末尾有 having count(1) = 1
。
P.S。 文档link答案很简单就可以了。
毫无疑问,您得到的是笛卡尔积,这会影响聚合。相反,聚合 before 进行连接:
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;
我遇到了一些 "complicated" 查询,例如:
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
但结果为我提供了一个 "wrong" 数据,因为它并没有真正包含这两个计数...
您能否描述无需大量嵌套查询即可解决此类问题的最 "cleaner" 方法?
如果它可能有帮助 - q2
类似于 q1
但在末尾有 having count(1) = 1
。
P.S。 文档link答案很简单就可以了。
毫无疑问,您得到的是笛卡尔积,这会影响聚合。相反,聚合 before 进行连接:
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;