我正在尝试编写一个查询,我可以每3个月在数据库的事务表中计算不同的user_id。
如果我执行以下操作,我可以手动获得结果
SELECT COUNT(DISTINCT(user_id)) FROM transactions WHERE DATE(created_at) BETWEEN "2011-01-01" AND "2011-03-31".
但是,如果我想在多年的季度时间内自动运行,那将需要永远。
有没有办法在单个查询中包装这类东西?
答案 0 :(得分:5)
SELECT COUNT(DISTINCT user_id),YEAR(created_at), QUARTER(created_at)
FROM transactions
GROUP BY YEAR(created_at), QUARTER(created_at)
答案 1 :(得分:3)
这会做你要问的吗?
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)
答案 2 :(得分:1)
这样的事情:
SELECT COUNT(DISTINCT USER_ID),
QUARTER(created_at),
YEAR(created_at)
FROM transactions
GROUP BY YEAR(created_at), QUARTER(created_at);