简体   繁体   English

MySQL连接并使用零对查询进行计数

[英]MySQL Joins and Counts Query with Zeros

I've been staring at so much SQL code my brain is practically mush. 我一直盯着太多的SQL代码,我的大脑几乎糊涂了。

I'll make it quick. 我会尽快。 Below are my table structures, with irrelevant columns omitted: 下面是我的表结构,省略了不相关的列:

attendance_history:              member_info:
_____________________            ________________________
|   Date   |   ID   |            |   ID   | Design Team |
|----------|--------|            |--------|-------------|
|   1/27   |    1   |            |    1   |     DT1     |
|   1/28   |    1   |            |    2   |     DT2     |
|   1/29   |    2   |            |    3   |     DT2     |
|   1/29   |    3   |            |--------|-------------|
|----------|--------|

My ultimate goal is to get an attendance average for every design team. 我的最终目标是使每个设计团队的出勤率平均。 But I believe I have all of the logic worked out except one part: I need to get the number of attendees for EACH design team for EACH date. 但是我相信我已经完成了所有逻辑,只有一部分: 我需要获得EACH设计团队在EACH日期的参加人数。

Here is an example of what I need: 这是我需要的一个例子:

__________________________________
|   Date   | Design Team | Count |
|----------|-------------|-------|
|   1/27   |     DT1     |   1   |
|   1/28   |     DT1     |   1   |
|   1/29   |     DT1     |   0   |
|   1/27   |     DT2     |   0   |
|   1/28   |     DT2     |   0   |
|   1/29   |     DT2     |   2   |
|----------|-------------|-------|

Any clues as to how I can achieve this? 关于如何实现这一目标的任何线索? Currently I have a ridiculously long script that only gets the counts for the design teams if someone was present. 目前,我有一个荒谬的脚本,只有在场的人才能获得设计团队的支持。 I need somehow get a 0 for a count in a row if there was nobody present for that day from that team. 如果那天那支球队没有人在场,我需要以某种方式连续计算0。

Thanks a ton, as always. 一如既往,非常感谢。

To get the zeros requires a bit of trickery. 要获得零,需要一些技巧。 You need to generate all the rows first (using a cross join ) and then left join in the attendance information: 您需要首先生成所有行(使用cross join ),然后在出勤信息中将其left join

select d.date, dt.design_team, coalesce(ddt.cnt, 0) as cnt
from (select distinct design_team from member_info) dt cross join
     (select distinct date from attendance_history) d left outer join
     (select ah.date, mi.design_team, count(*) as cnt
      from attendance_history ah join
           member_info mi
           on ah.id = mi.id
      group by ah.date, mi.design_team
     ) ddt
     on ddt.design_team = dt.design_team and ddt.date = d.date;

Edit : Fixed subquery to join on ah.id = mi.id instead of ah.id = ah.id. 编辑 :修复了子查询以加入ah.id = mi.id而不是ah.id = ah.id的问题。

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

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