我有两张桌子:
用户列表
故事列表 - 每个用户多个故事
我想知道用户的平均故事数。 (不是特定用户,适用于所有用户)
预期结果:每位用户平均故事数为2.3
尝试:
从(select count(distinct user_id)中选择avg(w)作为来自于user_id的故事组的w)a; 上面跑,但似乎不正确
也:
SELECT user_id,(SELECT COUNT(*)FROM stories w WHERE w.user_id = u.user_id)作为TotalStories FROM user u;
返回每个用户的平均故事,而不是整体
的平均值答案 0 :(得分:3)
首先,您需要知道每个用户的故事数量:
select count(s.id) as n
from users u left outer join stories s on u.id = s.user_id
group by u.id
然后只需将avg
应用于:
select avg(n)
from (
select count(s.id) as n
from users u left outer join stories s on u.id = s.user_id
group by u.id
) as dt
答案 1 :(得分:1)
SELECT COUNT(userid) AS totalusers, SUM(storycount) AS totalstories, SUM(storycount) / COUNT(userid) AS average_stories
FROM (
SELECT users.id AS userid, COUNT(stories.id) AS storycount
FROM users
LEFT JOIN stories ON (users.id = stories.user_id)
GROUP BY users.id
) AS child
内部查询会对每个用户的故事进行计数。外部查询计算总用户数,总故事数和每个用户平均数的故事数。