简体   繁体   中英

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.

SELECT Username, COUNT(DISTINCT(Date)) AS UniqueDaysAppeared
FROM Occurrences
GROUP BY Username

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM