Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count occurrences by day in SQL?

Newbie SQL question here -->

I've got an Occurrences table that contains a row for each time a user did something. A user can do the thing multiple times per day. It looks like this:

Date      Username
------    --------
1/1/9     User1
1/1/9     User1
1/1/9     User2
1/2/9     User1
1/2/9     User3
1/3/9     User1
1/3/9     User1
1/3/9     User1
1/3/9     User2
1/3/9     User3

I want a query to simply return the Username and the quantity (count) of unique days they appear. For the above data set, the result I'm looking for would be:

Username    UniqueDaysAppeared
--------    ------------------
User1       3
User2       2
User3       2

I keep getting screwed up because my query is returning not the count of unique days per user but rather the number of occurrences of the user overall.

like image 586
Robert Avatar asked Jan 24 '10 18:01

Robert


1 Answers

SELECT Username, COUNT(DISTINCT(Date)) AS UniqueDaysAppeared
FROM Occurrences
GROUP BY Username
like image 71
AdaTheDev Avatar answered Oct 26 '22 13:10

AdaTheDev