MySQL 有条件的 count+if 和 sum+if 函数结合使用

Mysql ⋅ tytrock ⋅ at 2019-02-27 18:09:40 ⋅ 8396 Reads

count函数

mysql中count函数用于统计数据表中的行的总数,或者根据查询结果统计某一列包含的行数,常见的用法如下 count(*) 计算表的总行数,包括空值 count(字段名) 计算指定列下的总行数,忽略空值(这点很重要,后面我们将利用这个特性)


if(expr, v1, v2)函数

if(expr, v1, v2) 函数的意思是,如果表达式expr为true(expr<>0 and expr <> NULL),则if()返回的是v1,否则返回v2


组合上述两个函数,可以在一条语句中统计出满足不同条件的行数

//统计type=1的数量
select count(if ( type = 1, true, null ) ) as cont from table

//统计不同的category下type=1的数量
select count(if ( type = 1, true, null ) ) as cont from table group by category

//统计type为NULL的数量
select count(if ( type IS NULL, true, null ) ) as cont from table

//统计type=1或type=2的数量
select count(if ( type (1,2), true, null ) ) as cont from table

//统计type=1并且category=2的数量
select count(if ( type=1 AND category=2, true, null ) ) as cont from table


同理sum+if的使用

SELECT SUM(if(category=1,size,0)) as sum from table;
//返回一个值类型的数值,统计category=1的size值总和,如果存在category=1则返回size值的总和,如果不存在category=1就返回0



参考:https://www.jianshu.com/p/d7a5e21d327e





This topic has been mark as Excenllent Topic.
Total Reply Count: 0
    No comments~~
    • publish_typography
    • publish_markdown
    • 支持表情,使用方法请见 Emoji 自动补全来咯,可用的 Emoji 请见 :metal: :point_right: Emoji 列表 :star: :sparkles:
    • publish_image
    • publish_draft
    Ctrl+Enter