我有下表" t1":
+----+---------+---------+-------+---------------------+
| id | name | country | isreg | time |
+----+---------+---------+-------+---------------------+
| 1 | felix | isr | 1 | 2016-10-02 15:23:32 |
| 2 | alex | rus | 0 | 2016-10-02 15:23:32 |
| 3 | avi | isr | 1 | 2016-10-02 15:23:32 |
| 4 | dima | rus | 1 | 2016-10-02 15:23:32 |
| 5 | nadav | isr | 0 | 2016-10-02 15:23:32 |
| 6 | vitaly | rus | 0 | 2016-10-02 15:23:32 |
| 7 | miko | ita | 1 | 2016-10-02 15:23:32 |
| 8 | jiji | ita | 1 | 2016-10-02 15:23:32 |
| 9 | vieri | ita | 0 | 2016-10-02 15:23:32 |
| 10 | maldini | ita | 1 | 2016-10-02 15:23:32 |
+----+---------+---------+-------+---------------------+
我想要实现的目标是:(基于isreg列)
+---------+------------+----------------+
| country | registered | notregistered |
+---------+------------+----------------+
| isr | 2 | 2 |
| rus | 1 | 2 |
| ita | 3 | 1 |
+---------+------------+----------------+
但是我在如何构建这个查询时遇到了麻烦,我想要解释一下如何做到这一点以及在执行类似的操作时我应该遵循的逻辑是什么?
编辑:我只需要计算每个国家的注册人数以及有多少人答案 0 :(得分:10)
您似乎只想要汇总:
select country, sum(isreg) as registered, sum(1 - isreg) as notregistered
from t1
group by country;
我不确定需要什么解释。逻辑似乎很清楚,并且join
不是必需的。
答案 1 :(得分:2)
您也可以使用此脚本
SELECT country,
SUM(CASE WHEN isreg=1 THEN 1 END) AS Registered,
SUM(CASE WHEN isreg=0 THEN 1 END) AS NotRegistered
From Table
GROUP BY country