Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Osaze Osoba
Osaze Osoba
875 Points

Finding cumulative sum of distinct occurrences in MySQL

I'm setting up a reporting dashboard for my client in Metabase. One view requested for was cumulative sum of new users (registered that month) making their first purchase.

Two tables hold this data

  1. "User" table shows User ID, Reg Date
  2. "Purchase" table shows Purchase Date, User ID, Item Details

What I have done so far is join both tables and display distinct users IDs registered between Date 1 & Date 2 who show up on the purchase table in the same month. But this gives me daily numbers, now I want to show daily cumulative. Here's my current code

SELECT count(DISTINCT p.`user_id`) Users_Activated, count(u.`id`) AS Users_Registered, date(p.`timestamp`) Day
FROM `purchase` p
INNER JOIN `user` u ON u.`id` = p.`user_id`
INNER JOIN `book` b ON b.`id` = p.`book_id`
WHERE date(u.`timestamp`) BETWEEN {{date1}} AND {{date2}} 
    AND date(p.`timestamp`) BETWEEN {{date3}} AND {{date4}}
GROUP BY date(p.`timestamp`)
ORDER BY date(p.`timestamp`) ASC

What do I do to show cumulative count of distinct IDs? Such that same user ID isn't counted twice

1 Answer

Steven Parker
Steven Parker
231,236 Points

I'm not familiar with "Metabase", but it sounds like you need another GROUP BY. Perhaps what you have here could be a CTE or derived table.

Osaze Osoba
Osaze Osoba
875 Points

Thanks Steven Parker , still a bit new to SQL so I'm reading up on derived tables now.