简体   繁体   中英

Combining multiple MySQL queries into one

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 can 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);

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