[英]How to determine the AVERAGE number of associated records
我有两个表:
我有以下查询告诉我评论中有 1 个或多个注释的百分比。
SELECT TRUNC(DATE_PART('day', CURRENT_DATE - r.created_at )/7) AS weeks_ago,
date(min(r.created_at)) AS "Date Start",
date(max(r.created_at)) AS "Date End",
count(*) as "reviews in Cohort",
AVG(has_note::int) as "Reviews w 1 or more Notes Ratio"
FROM (SELECT r.id, r.created_at,
( MAX(rs.note) IS NOT NULL ) as has_note
FROM reviews r JOIN
reviews_skills rs
ON r.id = rs.review_id
WHERE r.completed_at IS NOT NULL
AND r.created_at > '2019-01-01'
AND r.type = 'long_form'
GROUP BY r.id
) f
GROUP BY weeks_ago
ORDER BY weeks_ago DESC;
我要添加到此查询中的是:每次评论的平均笔记数量是多少?
如果我理解正确,您只需要子查询中的计数,然后是平均值:
SELECT TRUNC(DATE_PART('day', CURRENT_DATE - r.created_at )/7) AS weeks_ago,
date(min(r.created_at)) AS "Date Start",
date(max(r.created_at)) AS "Date End",
count(*) as "reviews in Cohort",
AVG(has_note::int) as "Reviews w 1 or more Notes Ratio",
AVG(num_notes) as avg_notes
FROM (SELECT r.id, r.created_at,
COUNT(rs.note) as num_notes,
( MAX(rs.note) IS NOT NULL ) as has_note
FROM reviews r JOIN
reviews_skills rs
ON r.id = rs.review_id
WHERE r.completed_at IS NOT NULL AND
r.created_at > '2019-01-01' AND
r.type = 'long_form'
GROUP BY r.id
) f
GROUP BY weeks_ago
ORDER BY weeks_ago DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.