gpt4 book ai didi

MySQL 连接表以进行多个条件的计数

转载 作者:行者123 更新时间:2023-11-29 19:44:42 26 4
gpt4 key购买 nike

尝试创建跨 3 个表的报告 - 公司、帐户、用户。对于每个公司,帐户中都有一个 ID。每个用户都有一个帐户。我可以很容易地获得总数,但我需要添加注册总数中的用户数量(用户名不为空)。

SELECT c.c_name, c.c_groupnumber, count(a.a_userid) AS TotalCount
FROM company c
LEFT JOIN account a ON c.c_groupnumber = a.a_groupnumber
WHERE a.a_deleted IS NULL
GROUP BY c.c_groupnumber
HAVING TotalCount > 0;

如何添加一个条件,使我的 user.u_username 计数不为空,同时保持我的 TotalCount?帐户和用户之间的链接是

a.a_userid = user.u_userid

tbl.company
c_id, c_groupnumber, c_name
1 1234 widgets, inc.
2 5678 joe's garage

tbl.user
u_userid, u_username, u_name
1 bill Bill Smith
2 frank Frank Johnson
3 NULL Jane Doe
4 mary Mary Stack
5 NULL Steve Spot

tbl.account
a_id, a_userid, a_groupnumber
100 1 1234
101 2 5678
102 3 5678
103 4 1234
104 5 1234

因此,使用上面非常简化的表格示例,公司“Widget's Inc.”有 3 名员工(bill smith、mary stack 和 steve Spot),这 3 名员工中有 2 名已注册(bill 和 mary),而 steve 尚未注册(用户名为空)。

Joe's Garage 有 2 名员工 - Frank 和 Jane,Frank 已注册,而 Jane 尚未注册。

我很乐意生成这样的报告:

Group      Company     Total Emp      Reg Emp
1234 Widgets Inc 3 2
5678 Joe's Garag 2 1

希望这能让问题更清楚吗?

最佳答案

如果您获取用户名的数量,然后执行 JOIN 操作,例如

SELECT c.c_name, c.c_groupnumber, count(a.a_userid) AS TotalCount,
xxx.username_count
FROM company c
LEFT JOIN account a ON c.c_groupnumber = a.a_groupnumber
LEFT JOIN ( select u_userid, count(u_username) username_count
from `user`
group by u_userid ) xxx ON a.a_userid = xxx.u_userid
WHERE a.a_deleted IS NULL
GROUP BY c.c_groupnumber
HAVING TotalCount > 0;

关于MySQL 连接表以进行多个条件的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103580/

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