MYSQL在单个查询中具有多个条件的多个COUNT()

时间:2015-11-10 05:06:02

标签: mysql

我是MYSQL中的新手。

我有一张如下表:

colmnA    colmnB
A           x
A           y
B           x
B           z
C           x
D           null

我想要达到的目标是:

SELECT
COUNT(distinct colmnA) WHERE colmnB IS NOT NULL AS deployed,
COUNT(distinct colmnA) WHERE colmnB IS NULL AS undeployed
FROM table

将导致:

deplyed    undeployed
3          1

有一种优雅的方法可以通过单个查询实现这一目标吗? 谢谢你的帮助

就我搜索而言,最封闭的解决方案是将SUM()与CASE条件相结合,例如:

SELECT SUM(CASE WHEN columnB IS NOT NULL then 1 else 0) AS deployed

但它将包含重复计数,并且无法将DISTINCT添加到SUM()中。

2 个答案:

答案 0 :(得分:1)

为什么不使用计数?

SELECT COUNT(DISTINCT CASE WHEN colmnB IS NOT NULL THEN colmnA END) deployed,
       COUNT(DISTINCT CASE WHEN colmnB IS NULL THEN colmnA END) undeployed
FROM   table;

答案 1 :(得分:0)

select max(deployed) as deployed, max(undeployed) as undeployed from ( select count(distinct columnA) as deployed, 0 as undeployed from testtable where columnb is not null union select 0 as deployed, count(distinct columnA) as undeployed from testtable where columnb is null ) as foo;

@ JRD的答案也有效。