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

Posted

技术标签:

【中文标题】从同一个表mysql存储过程中选择具有不同条件的多个计数【英文标题】:Selecting multiple count with different conditions from same table mysql stored procedure 【发布时间】:2019-10-03 11:13:33 【问题描述】:

我有一张像下面这样的表格

tbl_test

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

【问题讨论】:

请添加您的预期输出。并阅读 mysql 聚合函数。 VAL的最大值只能是3吗? 是的,最大值是 3@Ankit Bajpai 为什么是存储过程? 【参考方案1】:

您可以将条件聚合与case when expression 一起使用 -

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存储过程中选择具有不同条件的多个计数的主要内容,如果未能解决你的问题,请参考以下文章