I am trying to write a query where I can get a count on distinct user_id's in a transactions table of a database every 3 months.
I ca开发者_StackOverflow社区n achieve the result manually if I do the following
SELECT COUNT(DISTINCT(user_id)) FROM transactions WHERE DATE(created_at) BETWEEN "2011-01-01" AND "2011-03-31".
But if I want to run this automatically over years of quarterly periods it would take forever.
Is there a way to wrap this sort of thing up in a single query?
SELECT COUNT(DISTINCT user_id),YEAR(created_at), QUARTER(created_at)
FROM transactions
GROUP BY YEAR(created_at), QUARTER(created_at)
Will this do what you're asking?
select user_id, year(created_at) as `year`, quarter(created_at) as `quarter`, count(*)
from transactions
group by user_id, year(created_at), quarter(created_at)
What about something like this:
SELECT COUNT(DISTINCT USER_ID),
QUARTER(created_at),
YEAR(created_at)
FROM transactions
GROUP BY YEAR(created_at), QUARTER(created_at);
精彩评论