2016-07-14 121 views
0

我已經遇到了一些「複雜」的查詢,如:選擇查詢和相同的查詢具有結果

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 

但結果提供給我一個「錯誤」的數據,因爲它不是真的包含兩個計數...

請問您能描述一下最「清潔」的方式來解決這個問題,而沒有大量的嵌套查詢嗎?

如果它可能會有所幫助 - q2是類似於q1但末尾having count(1) = 1

P.S. 文檔鏈接會很好,答案很簡單。

+0

大概你需要一個連接。簡單的規則:*總是*使用明確的'JOIN'語法。 *從不*在'FROM'子句中使用逗號。 –

+0

我試過在q1.entity_id = q2.entity_id上使用q1 left join q2,但它也失敗了。 –

回答

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; 
+0

謝謝@戈登 –