如何在 MySQL 的同一列上计数和检索 null 和 not null?
---------------------------------------------------
id | name | visited | registDate |
---------------------------------------------------
1 | george | NULL | 2014-04-01 |
---------------------------------------------------
2 | Thomas | NULL | 2014-04-15 |
---------------------------------------------------
3 | Wilfred | 1 | 2014-04-24 |
---------------------------------------------------
4 | paul | 1 | 2014-04-10 |
---------------------------------------------------
5 | elina | NULL | 2014-05-03 |
---------------------------------------------------
6 | angela | NULL | 2014-04-13 |
---------------------------------------------------
7 | elina | 1 | 2014-05-18 |
---------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
month register visited not visited
---------------------------------------------
05-2014 2 1 1
---------------------------------------------
04-2014 5 2 3
---------------------------------------------
Run Code Online (Sandbox Code Playgroud)
尝试
SELECT
DATE_FORMAT(registDate, '%m-%Y') AS month,
COUNT(name) AS register,
SUM(!ISNULL(visited)) AS visited,
SUM(ISNULL(visited)) AS not_visited
FROM mytable
GROUP BY DATE_FORMAT(registDate, '%m-%Y');
Run Code Online (Sandbox Code Playgroud)
无需创建另一列。
要做的第一件事是“添加”月份的列:
select *, date_format(registDate, '%Y-%m') as regist_month
from mytable
Run Code Online (Sandbox Code Playgroud)
然后你就可以得到所有的计数:
select
regist_month
, count(registDate) as count_registered
, sum(case when visited is not null then 1 else 0 end) as count_visited
, sum(case when visited is null then 1 else 0 end) as count_not_visited
from (
select *, date_format(registDate, '%Y-%m') as regist_month
from mytable
) group by regist_month
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51313 次 |
| 最近记录: |