gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:12:26 30 4
gpt4 key购买 nike

下面是我的数据库表。

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 添加组即可。

最佳答案

您可以改为使用条件聚合:

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

关于mysql - 如何在 MySQL 中选择计数和减去子计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613923/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com