如何合并多个SQL查询

时间:2016-04-26 08:40:51

标签: mysql sql

我有一个名为Users的表。我正在尝试使用以下查询从中获取一些数据:

select name, lastname, gender, status, count(status = 'Trvl') as TrvlCount,
       count(status != 'Trvl') as NotTrvlCount, count(id) as TotalCount
from Users
group by name, lastname, gender, dob;

预期结果将是7列,具有唯一名称,姓氏,性别,dob(以避免重复)和不同状态的总和。但我无法纠正为什么所有3个计数列都显示相同的值或相同的总和值?

任何想法的人?提前谢谢。

2 个答案:

答案 0 :(得分:2)

你应该使用总和构造:

select name, lastname, gender, status, 
       sum(if(status = 'Trvl',  1, 0)) as TrvlCount,
       sum(if(status != 'Trvl',  1, 0)) as NotTrvlCount,
       count(id) as TotalCount
from Users
group by name, lastname, gender, dob;

答案 1 :(得分:0)

select name, lastname, gender, status, 
       (SELECT COUNT() FROM Users WHERE status = 'Trvl') as TrvlCount,
       (SELECT COUNT() FROM Users WHERE status <> 'Trvl') as NotTrvlCount,
       count(id) as TotalCount
from Users
group by name, lastname, gender, dob;

您也可以使用子查询来完成。