繁体   English   中英

SQL Union查询错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM