从同一 table mysql 存储过程中选择具有不同条件的多个计数
Selecting multiple count with different conditions from same table mysql stored procedure
我有一个 table 如下所示
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
您可以将条件聚合与 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
我有一个 table 如下所示
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
您可以将条件聚合与 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