将多个查询合并到SQL

时间:2018-02-05 15:49:56

标签: mysql sql

我在sql中遇到了一个问题,因为我对此很陌生。

我有三个查询

select count(*) as range1_50to60 from Customers where age between 50 and 60;

select count(*) as range2_30to40 from Customers where age between 30 and 40;

select count(*) as range3_20to30 from Customers where age between 20 and 30;

我们可以通过哪种方式将这些查询合并到一个查询中。

此致

Sameera

3 个答案:

答案 0 :(得分:3)

使用case表达式进行条件聚合:

select count(case when age between 50 and 60 then 1 end) as range1_50to60,
       count(case when age between 30 and 40 then 1 end) as range2_30to40,
       count(case when age between 20 and 30 then 1 end) as range3_20to30
from Customers

where age between 20 and 60

实际上并不需要WHERE子句,但可能会加快速度!

答案 1 :(得分:0)

您可以像这样使用SUM

SELECT SUM(IF(age between 50 and 60,1,0)) AS range1_50to60, 
       SUM(IF(age between 30 and 40,1,0)) AS range1_30to40, 
       SUM(IF(age between 20 and 30,1,0)) AS range1_20to30 
FROM Customers

答案 2 :(得分:0)

您可以尝试使用UNION ALL加入所有查询,它会像这样结束。

select count(*) as result from Customers where age between 50 and 60
union all
select count(*) as result from Customers where age between 30 and 40;
union all
select count(*) as result from Customers where age between 20 and 30;

结果将是:

row[0] for range1_50to60
row[1] for range2_30to40 
row[2] for range3_20to30