简体   繁体   English

MySQL连接表用于具有多个条件的计数

[英]MySQL join tables for counts with multiple conditions

Trying to create a report across 3 tables - company, account, user. 尝试跨3个表(公司,帐户,用户)创建报告。 For each company, there's an ID in account. 对于每个公司,帐户中都有一个ID。 Each user has an account. 每个用户都有一个帐户。 I can get totals easily enough, but I need to add count of how many users out of the total are registered (username is not null). 我可以很容易地获得总数,但是我需要增加总数中注册的用户数(用户名不为null)。

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;

How can I add in a condition that gives me a count of user.u_username not null while maintaining my TotalCount? 如何在保持TotalCount的情况下添加给我一个user.u_username不为null的计数的条件? The link between account and user is 帐户和用户之间的链接是

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

So using the above very simplified table example, company "Widget's Inc." 因此,使用上面非常简化的表格示例,公司“ Widget's Inc.” has 3 employees (bill smith, mary stack and steve spot), and of those 3 2 have registered (bill and mary), while steve has not (username is null). 拥有3名员工(bill smith,mary stack和steve spot),其中3名2已注册(bill和mary),而steve尚未注册(用户名为null)。

Joe's Garage has 2 employees - Frank and Jane, and Frank has registered, while Jane has not. Joe's Garage有2名员工-Frank和Jane,Frank已注册,而Jane没有。

I'd love to generate a report something like this: 我很想生成这样的报告:

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

Hopefully that makes the question clearer? 希望这使问题更清楚?

What if you get the count of username and then perform a JOIN with that like 如果你的用户名的计数,然后执行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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM