如何在MySQL中选择计数和减去子计数?

时间:2016-06-03 12:04:20

标签: mysql count group-by

以下是我的数据库表。

id     name    status     user_id
1      A       1          1
2      B       2          1 
3      C       2          1
4      D       2          1
5      E       3          1

6      F       2          2
7      G       2          2
8      H       1          2

我想计算user_id = 1和减去子计数记录的所有记录,其中user_id = 1 AND status = 2.结果应如下所示。

 count_all    count_status_2   count_left      user_id 
 5            3                2               1

下面是我的SQL查询。

SELECT a.count_all, b.count_status_2, (a.count_all - b.count_all_bought) AS count_left, a.user_id  
FROM
(
    SELECT COUNT(*) AS count_all, user_id FROM table WHERE user_id = 1
) a 
CROSS JOIN 
(
    SELECT COUNT(*) AS count_status_2 FROM table WHERE user_id = 1 AND status = 2
) b

但我不确定它是否是一种有效的解决方案。有没有更好的解决方案?

此外,我想通过user_id获得以下结果组。

count_all    count_status_2   count_left      user_id 
 5            3                2               1
 3            2                1               2 

我应该如何编写sql查询以获得第二个结果?很抱歉,如果我在一个问题中要求两个解决方案,因为它类似,只需按user_id添加分组。

1 个答案:

答案 0 :(得分:3)

您可以使用条件聚合

SELECT COUNT(*) AS count_all, 
       SUM(status=2) AS count_status_2,
       COUNT(*)- SUM(status=2) AS count_left,
       user_id 
FROM table 
WHERE user_id = 1
-- Add GROUP BY and remove above WHERE for ALL users
GROUP BY user_id