0

我一直在摆弄这个大约 20 分钟,尽管我可能会在这里得到一些帮助。我有两张表,是多对一的关系。用户(一个)和事件(很多)。简化后的表格如下所示:

users
-----------
user_id
group_id

events
-----------
user_id

我正在尝试生成一份报告,该报告将显示每组至少有一个事件的用户数量。所以结果集希望看起来像:

group_id   users_with_at_least_one_event
1          689
2          312
4

4 回答 4

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
于 2012-09-27T16:55:26.977 回答
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
于 2012-09-27T16:49:41.613 回答
0
SELECT users.group_id, COUNT(*) FROM users 
WHERE users.user_id IN (SELECT events.user_id FROM events)
于 2012-09-27T16:50:13.213 回答
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

也许?

于 2012-09-27T16:52:53.220 回答