[英]SQL Union query error
我正在尝试加入两个计数查询
SELECT COUNT(*) AS total FROM clients WHERE addedby = 1
UNION
SELECT COUNT(*) AS converts FROM clients WHERE addedby = 1 AND status = '6'
这返回的是
total
4
0
这是正确的数据,我期望的是
total converts
4 0
您不需要UNION
查询即可执行此操作。 SELECT A UNION SELECT B
返回A
的行,然后是B
的行(去重复);如果要从两个数据集中获取所有行,请使用UNION ALL
。
您想要的是这样的:
select
(select count(*) from clients where addedby=1) as total,
(select count(*) from clients where addedby=1 and status='6') as converts
另一种方法是使用case ... end
表达式,如果status='6'
则返回1
:
select
count(*) from clients,
sum(case when status='6' then 1 else 0 end) as converts
from clients
无需UNION
,只需一次即可完成。
SELECT COUNT(*) as total,
SUM(CASE status WHEN '6' THEN 1 ELSE 0 END) as converts
FROM clients;
编写此查询的最简单方法是条件聚合:
select count(*) as total, sum(status = '6') as converts
from cleints
where addedby = 1;
MySQL将布尔值视为整数,其中1
为true, 0
为false。 您可以对这些值进行求和以获得计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.