sql/impala:将多个查询(具有不同的where子句)组合成一个查询

iecba09b  于 2021-06-26  发布在  Impala
关注(0)|答案(2)|浏览(385)

我有以下疑问:

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

是否可以将这两个查询合并为一个查询?谢谢!

nfeuvbwi

nfeuvbwi1#

如果您认为返回的结果不同,那么应该使用“union all”,因为您只使用“union”,sql会对结果进行区分,从而影响查询的性能

50few1ms

50few1ms2#

很容易:)这应该适用于最常见的db引擎:

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

相关问题