开发者

Combining multiple MySQL queries into one

开发者 https://www.devze.com 2023-03-11 07:46 出处:网络
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 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消