用于选择多个计数列的MySQL查询

时间:2015-09-24 08:11:35

标签: mysql sql

我有一张这样的表 -

Table

我想运行一个查询,以便我可以得到类似的输出 -

enter image description here

我不清楚如何做到这一点。 所以,我所做的是 -

SELECT
        Count(* where status="Active") as count_active
        Count(* where status="Inctive") as count_inactive
        Count(* where status="Biase") as count_biase
    FROM `subscribers`

收到错误,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

可以使用Case表达式实现此目的。

<强>查询

select 
count(case when status = 'Active' then 1 else null end) as Active_Count,
count(case when status = 'Inactive' then 1 else null end) as Inctive_Count,
count(case when status = 'Biase' then 1 else null end) as Biase_Count
from tbl_name;

SQL Fiddle

答案 1 :(得分:0)

这是将它放在一个寄存器中的方法:

SELECT 
(SELECT count(id) FROM new_table where status = 'Active') as Active_Count,
(SELECT count(id) FROM new_table where status = 'Inactive') as Inctive_Count,
(SELECT count(id) FROM new_table where status = 'Biase') as Biase_Count;