2016-08-16 61 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将区分结果以影响查询