如何编写SQL查询以按类型进行选择和分组以及按类型进行计数? [英] How to write the sql query to select and group by type and count per type?

查看:701
本文介绍了如何编写SQL查询以按类型进行选择和分组以及按类型进行计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的数据库表.

id     name    type   
1      a       1
2      a       1
3      a       1
4      a       0
5      a       0
6      b       1
7      b       1
8      b       0
9      b       0
10     b       0
11     c       1
12     c       1
13     c       0

我想按类型进行选择和分组,并按类型进行计数.如何编写sql查询以获取以下结果?

I would like to select and group by type and count per type. How to write the sql query to get the following results?

name    count_type_0    count_type_1
a       2               3
b       3               2
c       1               2

推荐答案

只需使用条件聚合:

select name, sum(type = 0) as count_0, sum(type = 1) as count_1
from t
group by name;

这使用MySQL功能,将布尔值视为数字上下文中的数字,其中0表示false,1表示true.因此,将这些值相加即可计算表达式为真的次数.

This uses a MySQL feature that treats boolean values as numbers in a numeric context, with 0 for false and 1 for true. Hence, adding up the values counts the number of times the expression is true.

这篇关于如何编写SQL查询以按类型进行选择和分组以及按类型进行计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆