计算列中的空值和非空值


10

如何在MySQL的同一列上计算和检索null和not null?

mytable

---------------------------------------------------
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 |
---------------------------------------------------

预期结果

month      register    visited    not visited
---------------------------------------------
05-2014       2           1          1   
---------------------------------------------
04-2014       5           2          3
---------------------------------------------

Answers:


6

尝试

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');

无需创建另一列。


2

首先要做的是“添加”月份的列:

select *, date_format(registDate, '%Y-%m') as regist_month
from mytable

然后,您可以获得所有计数:

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

您可以使用计数,而不是总和,缩短表达了一下:count(visited)。count(<column>)将仅计数不为null。如果添加另一层嵌套,则可以将count_not_visited确定为count_registered - count_visited
Lennart

1

例如,为了计算一列的所有非null值col1,您可以使用count(col1) as cnt_col1。但是,更明显的是,您可以使用sum()函数和IS NOT NULL运算符,成为sum(col1 IS NOT NULL)。这是因为IS NOT NULL运算符返回一个int:1表示true,0表示false。

为了对空值进行计数,可以使用IS NULL运算符,该运算符在值空时将返回1。像以前一样,与sum()操作员一起。

鉴于此,为了获得每个月的注册,访问和非访问量,可以执行以下操作:

SELECT
date_format(registDate, '%m-%Y') as month,
count(registDate) as register,
sum(visited is not null) as visited,
sum(visited is null) as 'not visited'
GROUP BY
date_format(registDate, '%m-%Y')

请注意,您可以仅通过引用,双引号或使用反引号(`)来输出带有空格的“未访问”列。

选择和按月分组的另一种方法是将月与年连接起来,像这样concat(month(registDate), '-', date(registDate))。但是它不太优雅。

case其他答复建议操作人员是完全有效的,但我觉得它更充足的其他情形。而且更冗长。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.