计算用户未响应的事件数量

时间:2019-12-03 17:10:36

标签: mysql sql left-join

考虑到下面提供的表格,我希望能够统计仍然没有提供Events的{​​{1}}和User的出现次数。

availability

users

| name | id | |---------|----| | John | 1 | | Francis | 2 | | Peter | 3 | | Mike | 4 |

events

| id | name | |----|---------| | 1 | Event 1 | | 2 | Event 2 |

availability

那么预期的答案将是:

预期答案:

| answer | event_id | user_id |
|--------|----------|---------|
|    yes |        1 |       1 |
|    yes |        2 |       1 |
|     no |        1 |       2 |
|  maybe |        2 |       4 |

我已经能够查询每个成员响应了多少个事件,但是可以查询多少个未响应

DBFiddle:https://www.db-fiddle.com/f/mwv4F1wYZ9UxB56L9mMjFQ/1

SQL:

| user_id | count |
|---------|-------|
| 1       | 0     |
| 2       | 1     |
| 3       | 2     |
| 4       | 1     |

2 个答案:

答案 0 :(得分:2)

您可以cross join个表usersevents来生成所有可能的组合,然后left join个表availability。然后,聚合和条件sum()会给您预期的结果。

select
    u.id user_id,
    sum(case when a.event_id is null then 1 else 0 end) cnt
from users u
cross join events e
left join availability a 
    on a.event_id = e.id and a.user_id = u.id
group by u.id
order by u.id

Demo on DB Fiddle

user_id | cnt
------: | --:
      1 |   0
      2 |   1
      3 |   2
      4 |   1

答案 1 :(得分:1)

您还可以通过预先汇总可用性表来解决此问题:

select u.user_id, (e.num_events - a.cnt)
from users u left join
     (select a.user_id, count(*) as cnt
      from availability a
      group by a.user_id
     ) a 
     on u.user_id = a.user_id cross join
     (select count(*) as num_events from events) e;