同一列上多个条件的联合结果

时间:2015-11-30 07:22:15

标签: mysql

我想根据具有多个where条件的单个列选择两列数据。

SELECT country.countryname,COUNT(users.uid) as cnt
FROM users
JOIN country
ON users.country = country.countrycode
WHERE users.useractivated = 1 AND users.status = 'on'
GROUP BY users.country
ORDER BY cnt DESC
LIMIT 30

此查询为我提供了主要的cnt列。现在我想要一个额外的cnt2列

选择以下条件

users.status <> 'on'

但仅适用于之前主要选择的30个国家。

所以输出看起来像

+----------------+-------+---------+
|   countryname  |   cnt | cnt2    |
+----------------+-------+---------+
| USA            | 1012  |  12     |
| CANADA         | 1125  |  135    |
| ...            | ...   |  ...    |
+----------------+-------+---------+

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

如果

使用SUM
SUM(IF(users.status = 'on', 1, 0)) AS cnt

SUM(IF(users.status <> 'on', 1, 0)) AS cnt2

查询: -

SELECT country.countryname,
SUM(IF(users.status = 'on', 1, 0)) AS cnt,
SUM(IF(users.status <> 'on', 1, 0)) AS cnt2
FROM users
JOIN country
ON users.country = country.countrycode
WHERE users.useractivated = 1
GROUP BY users.country
ORDER BY cnt DESC
LIMIT 30