Im trying to find the total count of event names. My table has a column Royalty_Month and Event_Combined. If an event appears in Month A, I dont want to count it in Month B.
This is the query I have, but its not excluding events that occurred in the previous months.
SELECT
Royalty_Month,
COUNT(DISTINCT(Event_Combined)) As Event_Count
FROM Agency
GROUP BY Royalty_Month
ORDER BY Royalty_Month ASC
Sample Data:
Royalty_Month | Event_Combined |
---|---|
2010-05-01 | Event A |
2010-06-01 | Event B |
2010-07-01 | Event C |
2010-07-01 | Event B |
2010-07-01 | Event D |
2010-07-01 | Event D |
2010-07-01 | Event D |
2010-07-01 | Event E |
2010-07-01 | Event E |
2010-07-01 | Event E |
2010-07-01 | Event E |
2010-07-01 | Event E |
2010-08-01 | Event F |
2010-08-01 | Event F |
2010-09-01 | Event E |
2010-09-01 | Event E |
2010-09-01 | Event G |
2010-09-01 | Event G |
2010-09-01 | Event G |
2010-09-01 | Event H |
2010-09-01 | Event H |
2010-09-01 | Event H |
2010-10-01 | Event E |
2010-10-01 | Event F |
2010-10-01 | Event G |
2010-10-01 | Event G |
Expected Output:
Royalty_Month | Total_Events |
---|---|
2010-05-01 | 1 |
2010-06-01 | 1 |
2010-07-01 | 3 |
2010-08-01 | 1 |
2010-09-01 | 2 |
2010-10-01 | 0 |
3
Answers
If you want to count rows by
month
, use defaultgroup by month
– this will group all rows which fall in a single month.To fetch the count of rows in a single month, your query should be
which will generate
Live example
Read more on default date time functions here
In MySQL 8.0, one option is to:
ROW_NUMBER
window functionyou can try this on previous versions as well as new version of MySQL: