假设我们有以下数据集
+----------+
| Column 1 |
+----------+
| NULL |
| NULL |
| NULL |
| NULL |
| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 2 |
+----------+
然后让我们运行
select count(`Column 1`),
`Column 1`,
(select count(*)
from testingtable) as total
from testingtable
group by `Column 1`
获得以下结果:
+-------------------+----------+-------+
| count(`Column 1`) | Column 1 | total |
+-------------------+----------+-------+
| 0 | NULL | 10 |
| 4 | 1 | 10 |
| 2 | 2 | 10 |
+-------------------+----------+-------+
如何在空值上聚合(在这种情况下使用count
)会返回NULL
而不是4
(在这种情况下)?我知道大多数SQL引擎中的null = null # => null
(甚至是postgres),但不应该在必要时将分组处理切换到is
?你如何正确处理这个案子?
注意:Postgres会产生相同的结果。
答案 0 :(得分:3)
由于count
函数包含null
,因此无法计算数量
count(*)
而不是
count(`Column 1`)
你可以试试这个。
select count(*),
`Column 1`,
(select count(*)
from testingtable) as total
from testingtable
group by `Column 1`
答案 1 :(得分:1)
http://sqlfiddle.com/#!9/9a0bd/6
SELECT count(*),
`Column1`,
t.total
FROM testingtable
LEFT JOIN (
SELECT count(*) as total
FROM testingtable
) t
ON 1=1
GROUP BY `Column1`
或者我怀疑你甚至不需要你的total
字段,只是:
SELECT count(*),
`Column1`
FROM testingtable
GROUP BY `Column1`
WITH ROLLUP
答案 2 :(得分:1)
使用select
select
中使用另一个over()
的另一种方法
select distinct `column 1`,
count(*) over(partition by `column 1`) as `Column 1`,
count(*) over() as total
from testingtable