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

Mysql tytrock ⋅ 于 2019-02-27 18:09:40 ⋅ 4207 阅读

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


同理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





本帖已被设为精华帖!
回复数量: 0
    暂无评论~~
    • 请注意单词拼写,以及中英文排版,参考此页
    • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`, 更多语法请见这里 Markdown 语法
    • 支持表情,使用方法请见 Emoji 自动补全来咯,可用的 Emoji 请见 :metal: :point_right: Emoji 列表 :star: :sparkles:
    • 上传图片, 支持拖拽和剪切板黏贴上传, 格式限制 - jpg, png, gif
    • 发布框支持本地存储功能,会在内容变更时保存,「提交」按钮点击时清空
    Ctrl+Enter