2016-08-16 55 views
0

我有以下查詢:SQL /帕拉:合併多個查詢(用不同的WHERE子句中)到一個

'select team, count(distinct id) as distinct_id_count_w1 from myTable where timestamp > t1 and timestamp < t2 group by team' 

'select team, count(distinct id) as distinct_id_count_w2 from myTable where timestamp > t2 and timestamp < t3 group by team' 

是否有可能這兩個查詢合併成一個?謝謝!

回答

1

輕鬆:)這應該上最常見的數據庫引擎的工作原理:

select team, count(distinct id) as distinct_id_count_w1, null as distinct_id_count_w2 from myTable where timestamp > t1 and timestamp < t2 group by team 

UNION ALL 

select team, null as distinct_id_count_w1, count(distinct id) as distinct_id_count_w2 from myTable where timestamp > t2 and timestamp < t3 group by team 

如毛豆說,你可能需要閱讀每隊兩個結果。這是不是從問題本身清楚,但可以用此方式解決:

SELECT 
    COALESCE(interval1.team interval2.team) AS team, 
    interval1.distinct_id_count_w1, 
    interval2.distinct_id_count_w2 
FROM (
    select team, count(distinct id) as distinct_id_count_w1 from myTable where timestamp > t1 and timestamp < t2 group by team 
) AS interval1 
FULL OUTER JOIN 
(
    select team, count(distinct id) as distinct_id_count_w2 from myTable where timestamp > t2 and timestamp < t3 group by team 
) AS interval2 
ON interval1.team IS NULL OR interval2.team IS NULL OR interval1.team = interval2.team 
+0

的性能,但結果不會加入使用團隊。一半的行有distinct_id_count_w2 =無,另一半有distinct_id_count_w1 =無。每行應具有有效值distinct_id_count_w1和有效值distinct_id_count_w2 – Edamame

0

如果u認爲,返回的結果是不同的,U應使用「UNION ALL」,因爲ü只能用「聯盟」的工作,SQL將區分結果以影響查詢