我现在约20分钟一直在努力,尽管我可能会在这里得到一些帮助。我有两张桌子,以多对一的关系。用户(一)和事件(很多)。简化的表格如下所示:
users
-----------
user_id
group_id
events
-----------
user_id
我正在尝试生成一个报告,该报告将显示每个组至少有一个事件的用户数。所以结果集有望看起来像:
group_id users_with_at_least_one_event
1 689
2 312
答案 0 :(得分:2)
SELECT group_id, count(*) users_with_at_least_one_event
FROM
(
SELECT u.user_id, u.group_id, count(*) as event_count
FROM users u
JOIN events e
ON u.user_id = e.user_id
GROUP BY u.user_id, u.group_id
HAVING count(*) > 1
) sub
GROUP BY group_id
答案 1 :(得分:0)
尝试
select users.group_id, count(distinct users.user_id) as users_with_at_least_one_event
from
users, events
where users.user_id = events.user_id
group by users.group_id
答案 2 :(得分:0)
SELECT users.group_id, COUNT(*) FROM users
WHERE users.user_id IN (SELECT events.user_id FROM events)
答案 3 :(得分:0)
SELECT group_id, COUNT(users.user_id) AS users_with_at_least_one_event,
FROM users, events
WHERE users.user_id = events.user_id
GROUP BY group_id
可能?