我想要一个查询,该查询给出日期为“ april2018”的重复区域计数 查询的预期输出
显示的表格
+---------+--------------+
| region | Date |
+---------+--------------+
| africa | april2018 |
| africa | may2018 |
| africa | may2018 |
| america | jan2018 |
| america | jan2018 |
| africa | april2018 |
| africa | may2018 |
| africa | may2018 |
| india | jan2018 |
| india | jan2018 |
+---------+--------------+
预期结果
+----------+---------+
| region | Count |
+----------+---------+
| africa | 2 |
| america | 0 |
| india | 0 |
+----------+---------+
答案 0 :(得分:1)
将case when
与计数一起使用
select region, coalesce(count(case when Date = 'april2018' then 1 end),0) as count
from tablname
group by region
答案 1 :(得分:0)
您可以根据要求执行以下查询以获取结果。
SELECT Region, COUNT(*) AS Cnt
FROM Region
WHERE Date = 'April2018'
GROUP BY Region
答案 2 :(得分:0)
我添加了一个主键以获得您的预期结果
mysql> select * from region_date;
+---------+-----------+----+
| region | date | id |
+---------+-----------+----+
| africa | april2018 | 1 |
| africa | may2018 | 2 |
| africa | may2018 | 3 |
| america | jan2018 | 4 |
| america | jan2018 | 5 |
| africa | april2018 | 6 |
| africa | may2018 | 7 |
| africa | may2018 | 8 |
| india | jan2018 | 9 |
| india | jan2018 | 10 |
+---------+-----------+----+
10 rows in set (0.00 sec)
mysql> select count(sub), inn.region from
(select
i.region,
(select s.date from region_date s where s.id = i.id and s.date = 'april2018' limit 1) as sub,
date
from region_date i) as inn group by region;
+------------+---------+
| count(sub) | region |
+------------+---------+
| 2 | africa |
| 0 | america |
| 0 | india |
+------------+---------+
3 rows in set (0.00 sec)
答案 3 :(得分:0)
这是另一种简单的方法:
SELECT Region, SUM(Date='april2018') as Count
FROM TableName
GROUP BY Region;