mysql - 从同一个表mysql存储过程中选择具有不同条件的多个计数

标签 mysql sql mariadb stored-functions

我有如下表格

tbl_测试

test_id     name    val

1            ab       1
2            ac       1
3            ad       2
4            af       3
5            fg       2
6            ss       1
7            dd       3

我想在同一个查询中根据 val 对名称进行计数

尝试过

(select count(name )   where val='1' ) as one,
(select count(name )   where val='2' ) as two,
(select count(name )   where val='3' ) as thr

预期输出

one  two  thr

3     2   2

最佳答案

您可以使用条件聚合和 case when 表达式 -

select 
    count(case when val=1 then name end) as one,
    count(case when val=2 then name end) as two,
    count(case when val=3 then name end) as thr
from tbl_test

关于mysql - 从同一个表mysql存储过程中选择具有不同条件的多个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58217973/

相关文章:

php - 在逗号分隔列表中搜索字符串

php - MySQL查询中基于日期的第n条记录

mysql - 由于在 MySQL 中使用保留字作为表名或列名而导致的语法错误

sql - 数据库插入机制

mysql - 总结一周的统计记录

mysql - 查询总是返回1064语法错误

php - 如何使用 PHP 7 和 MySQL 将文件从 POST 插入到 longblob 列中?

sql - MySQL - 为唯一列分组 dayname()

PHP 未与服务器连接

sql - 使用 Postgresql 提取第二个找到的匹配子字符串