PostgreSQL 使用 count filter 统计不同条件下的数量

PostgreSQL 统计 About 795 words

需求

统计不同年龄段的学生数量:总学生数、年龄6~10岁学生数量(小学)、年龄11~14岁学生数量(初中)、年龄15~17岁学生数量(高中)。

数据准备

create table student (
    name text,
    age int
)

insert into student
values ('张三', 10), ('李四', 11), ('王五', 12), ('赵六', 16);

SQL

count filter中可以添加where条件,按条件分别进行count记数。

select count(*) as 总学生数,
       count(*) filter ( where age >= 6 and age <= 10 ) as 小学生数,
       count(*) filter ( where age >= 11 and age <= 14 ) as 初中生数,
       count(*) filter ( where age >= 15 and age <= 17 ) as 高中生数
from student
group by age;

输出

 总学生数 | 小学生数 | 初中生数 | 高中生数
----------+----------+----------+----------
        1 |        0 |        1 |        0
        1 |        1 |        0 |        0
        1 |        0 |        0 |        1
        1 |        0 |        1 |        0
(4 rows)

补充

以此类推,可以用在如统计不同状态的订单数量(支付成功量、支付失败量)等。

Views: 526 · Posted: 2024-06-07

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today On History
Browsing Refresh