簡體   English   中英

SQL / Impala:將多個查詢(具有不同的where子句)組合為一個

[英]SQL/Impala: combined multiple query (with different where clause) into one

我有以下查詢:

'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'

是否可以將這兩個查詢合並為一個? 謝謝!

輕松:)這應該適用於大多數常見的數據庫引擎:

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

正如Edamame所說,您可能希望每個團隊閱讀兩個結果。 從問題本身尚不清楚,但是可以通過以下方式解決:

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

如果您認為返回的結果不同,則應使用“ UNION ALL”,因為您只能與“ UNION”一起使用,sql將區分結果以影響查詢的性能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM