Add username to two queries

Hi, I decide to open new topic for this:

Top quality users in last six months

Well, for the Top quality users in last six months, I used the 2nd version from query.

And I added the username; and a :limit param.

-- [params]
-- int :limit = 20
SELECT 
    sum(p.score) / count(p) as "average score per post", 
    count(p.id) as post_count, 
    -- p.user_id, 
    u.username
FROM posts p
JOIN users u ON u.id = p.user_id
WHERE p.created_at >= CURRENT_DATE - INTERVAL '6 month'
  AND NOT u.admin
  AND u.active
GROUP by user_id, u.views, u.username
HAVING count(p.id) > 50
ORDER BY sum(p.score) / count(p) DESC
LIMIT :limit

Top 50 posters

For the “Top 50 posters”'s query, I used this version, and I added param for limit, and the username you need.

-- [params]
-- int :months_ago = 1
-- int :limit = 50
WITH query_period AS (
SELECT
date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,
date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end
),

user_posts_in_period AS (
SELECT
p.user_id, u.username
FROM users u, posts p
INNER JOIN query_period qp
ON p.created_at >= qp.period_start
AND p.created_at <= qp.period_end
WHERE p.user_id > 0
AND u.id = p.user_id
)

SELECT
up.username,
-- up.user_id,
count(1) as post_count
FROM user_posts_in_period up
GROUP BY up.user_id, up.username
ORDER BY post_count DESC
LIMIT :limit

Let me know if it works as you want.

Regards

7 Likes

Thanks so much @SidV, that’s exactly what I needed! :grinning:

2 Likes