我有一个包含 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/