최상위 카테고리별 게시물 수 및 사용자
각 최상위 카테고리에 기여한 사용자 목록과 그들이 기여한 게시물 수를 나타냅니다. 게시물에는 주제 시작 게시물과 그 아래 댓글이 모두 포함됩니다. 쿼리를 편집하여 최상위 카테고리를 하나만 선택하여 볼 수 있습니다.
/* 하위 및 최상위 카테고리에서 코드 합계 */
SELECT
category_id, username AS "User", SUM(contributions) AS "Post Count"
FROM (
/* 최상위 카테고리에 주제가 있는 사용자. */
SELECT
topics.category_id, COUNT(*) AS contributions, users.username
FROM users
INNER JOIN posts ON users.id = posts.user_id
INNER JOIN topics ON posts.topic_id = topics.id
INNER JOIN categories ON topics.category_id = categories.id
WHERE categories.parent_category_id IS NULL
GROUP BY category_id, username
UNION
/* 최상위 카테고리별 하위 카테고리에 주제가 있는 사용자. */
SELECT
categories.parent_category_id AS category_id, COUNT(*) AS contributions, users.username
FROM users
INNER JOIN posts ON users.id = posts.user_id
INNER JOIN topics ON posts.topic_id = topics.id
INNER JOIN categories ON topics.category_id = categories.id
WHERE categories.parent_category_id IS NOT NULL
GROUP BY categories.parent_category_id, username
) AS users_by_category
INNER JOIN categories ON category_id = categories.id
GROUP BY category_id, username
HAVING SUM(contributions) > 5
ORDER BY category_id, "Post Count" DESC