有几个在单个查询中选择count(*)

时间:2015-11-27 05:53:07

标签: mysql

enter image description here

我有一个像上面这样的mysql表(tbl_subscriptiondetails)。这是最后一列,即 ' test_status'可能有可能的值C,S&仅限Y. 使用单个查询我想以这种方式获取数据 如下图所示

enter image description here

但是我使用的查询给了我不想要的结果。我的查询是

    SELECT pkg_name, 
(SELECT COUNT(*) FROM tbl_subscriptiondetails WHERE test_status='C' AND mem_id=3) AS completed, 
(SELECT COUNT(*) FROM tbl_subscriptiondetails WHERE test_status='S' AND mem_id=3) AS started, 
(SELECT COUNT(*) FROM tbl_subscriptiondetails WHERE test_status='Y' AND mem_id=3) AS remaining 
FROM tbl_subscriptiondetails 
WHERE mem_id=3 
GROUP BY pkg_name

结果是 enter image description here

enter image description here

请告知错误。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您正在为每个计数运行子查询,而不是作为主查询的一部分进行计数。因此,您的过滤条件不符合您的预期。您可以像这样更改它,以进行条件计数:

SELECT pkg_name, 
SUM( case when test_status='C' then 1 else 0 end) AS completed, 
SUM( case when test_status='S' then 1 else 0 end) AS started, 
SUM( case when test_status='Y' then 1 else 0 end) AS remaining 
FROM  tbl
WHERE mem_id = 3
GROUP BY pkg_name

Demo