sql - 如何对具有 NULL 值的字段进行分组?

标签 sql sqlite null count group-by

我有一个包含 2 个字段的表

 x          y
----       ----
 1         null            
 2          5
 3          5
 4         null
 5         null
 6          10
 7          5

我的 SQLite 查询是

select y,count(y)
from mytable
group by y

结果是

null    0
 5      3
 10     1

期望看到null 3.
但输出为空 0。
这是什么意思?

最佳答案

From Aggregate Functions in SQLite

The count(X) function returns a count of the number of times that X is not NULL in a group. The count(*) function (with no arguments) returns the total number of rows in the group.

因此,COUNT 函数不计算 NULL 因此使用 COUNT(*) 而不是 COUNT(y).

SELECT y, COUNT(*) AS COUNT
FROM mytable
GROUP BY y

或者您也可以像这样使用 COUNT(x)

SELECT y, COUNT(x) AS COUNT
FROM mytable
GROUP BY y

See this SQLFiddle

关于sql - 如何对具有 NULL 值的字段进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12870094/

相关文章:

MySQL 更新周年纪念日

sql - 如何对三个表使用 MAX 函数?

sql - 如何将多行插入到 SQLite 3 表中?

null - 不在 Presto 与 Spark SQL 的实现中

c++ - 测试指针的有效性 (C/C++)

SQL 选择特定列的第一行记录

php - 在 php 中创建嵌套组时打破循环

java - 如果使用 JDBC 通过检查结果集在表(SQLite)中没有记录,则将 0 放入 arraylist

sql - SELECT hex(name || age) AS X FROM Ages ORDER BY X

mysql - 为什么索引列在查询 `IS NULL` 时返回结果会很慢?