当前位置:首页 > 数据库 > 正文内容

Sql根据不同条件统计总数

2024-11-29数据库2

经常会遇到根据不同的条件统计总数的问题,一般有两种写法:count和sum都可以
数据准备:

方法一 :Count

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SELECT
    COUNT(
        CASE
        WHEN age > 20
        AND age < 25 THEN
            1
        ELSE
            NULL
        END
    ) AS cnt0,
    COUNT(
        CASE
        WHEN age >= 25
        AND age < 30 THEN
            1
        ELSE
            NULL
        END
    ) AS cnt1
FROM
    USER;

结果:

方法二:sum

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SELECT
    SUM(
        CASE
        WHEN age > 20
        AND age < 25 THEN
            1
        ELSE
            0
        END
    ) AS cnt0,
    SUM(
        CASE
        WHEN age >= 25
        AND age < 30 THEN
            1
        ELSE
            0
        END
    ) AS cnt1
FROM
    USER;

结果:

当然也可以和count代码一样ELSE后面也写为NULL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SELECT
    SUM(
        CASE
        WHEN age > 20
        AND age < 25 THEN
            1
        ELSE
            NULL
        END
    ) AS cnt0,
    SUM(
        CASE
        WHEN age >= 25
        AND age < 30 THEN
            1
        ELSE
            NULL
        END
    ) AS cnt1
FROM
    USER;

后记

其实原理很简单,count统计的时候有满足条件的就加1,没有满足的变为NULL,我们知道聚合函数统计的时候是忽略null值的;而sum原理和coun相似,不过ELSE后面可以是0或者NULL。