How can I find the team with the most active sellers (highest number of software sales per user per day)?

Viewed 58

How can I find the team with the most active sellers (highest number of software sales per user per day)? I wanted to do something like this query but it doesn't feel quiet right

SELECT users.team_id, count(*) as sales FROM users
INNER JOIN activity ON users.user_id = activity.user_id
WHERE activity.sales = software
GROUP BY users.team_id
ORDER BY sale DESC

My user table looks like this:

user_id       team_id  
0               62  
1               32      
2               21      

While my activity table looks like this:

user_id      sale_date              sale
1            2019-05-02 11:02:39    hardware    
2            2018-05-02 11:02:53    software    
2            2019-06-02 11:42:33    software
1 Answers

It sounds like this is a step-by-step query, so let's start small with the innermost part: get the sales counts per user per day.

SELECT sale_date, user_id, count(*) as sales
WHERE sale = 'software'
GROUP BY sale_date, user_id

Then we can get the most active user for each day:

SELECT DISTINCT ON (sale_date) sale_date, user_id
FROM (
    SELECT sale_date, user_id, count(*) as sales
    WHERE sale = 'software'
    GROUP BY sale_date, user_id
) AS counts_by_date_and_user
ORDER BY sale_date, sales -- consider breaking ties somehow

Then we can count how often a user was the most active of the day, sort by that, and get their team id.

SELECT team_id, user_id, count(*) as days
FROM (
    SELECT DISTINCT ON (sale_date) sale_date, user_id
    FROM (
        SELECT sale_date, user_id, count(*) as sales
        WHERE sale = 'software'
        GROUP BY sale_date, user_id
    ) AS counts_by_date_and_user
    ORDER BY sale_date, sales -- consider breaking ties somehow
) AS most_active
JOIN users USING (user_id)
GROUP BY user_id
ORDER BY days DESC
Related