1、我们知道,SQL语句中用count函数统计记录数量,配合distinct关键字可以统计非重复的记录数量。例如:
select count(*), count(city_name), count(distinct city_name) from tb_county
- 1
查询结果是:
count(*) | count(city_name) | count(distinct city_name) |
---|---|---|
2534 | 2534 | 363 |
select count(*), count(city_name), count(distinct city_name)
from tb_county
where xs_code like '23%'
or xs_code like '24%'
- 1
- 2
- 3
- 4
查询结果是:
count(*) | count(city_name) | count(distinct city_name) |
---|---|---|
85 | 85 | 16 |
2、如果我们需要统计总记录数量和某种条件下的数量,可以用 sum函数 函数和case when语句配合,例如:
select count(*),
sum(case when xs_code like '23%' or xs_code like '24%'
then 1
else 0
end)
from tb_county
- 1
- 2
- 3
- 4
- 5
- 6
查询结果是:
count(*) | sum |
---|---|
2534 | 85 |
3、如果我们需要统计总记录数量和某种条件下非重复的记录数量,用上面的sum函数就不行了。这时我们可以用count函数和case when语句配合,满足条件取字段值,否则为空(null),因为count函数是不统计空值的,所以可以统计该条件下的记录数量(和上面的sum函数功能一样),如果再配合distinct关键字,就可以统计该条件下非重复的记录数量了。例如:
select count(*),count(city_name),count(distinct city_name),
count(case
when xs_code like '23%' or xs_code like '24%'
then city_name
else null
end),
count(distinct case
when xs_code like '23%' or xs_code like '24%'
then city_name
else null
end)
from tb_county
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
查询结果是:
count(*) | count(city_name) | count(distinct city_name) | count(case | count(distinct case |
---|---|---|---|---|
2534 | 2534 | 363 | 85 | 16 |
这个功能在统计中很有用,尤其是我们需要统计去重复的总量和分量的时候。
上面语句中的else还可以不写,因为默认情况下不写就是空值(null)。即:
select count(*),count(city_name),count(distinct city_name),
count(case
when xs_code like '23%' or xs_code like '24%'
then city_name
end),
count(distinct case
when xs_code like '23%' or xs_code like '24%'
then city_name
end)
from tb_county