我在计算时间范围内的多个字段时遇到问题。 我有下表:
# date, count, fb_user_count, email_user_count, reg_dt
'2015-10-27', '11', '6', '5', '2015-11-02 13:59:14'
'2015-10-26', '3', '1', '2', '2015-11-02 13:59:10'
我想获得每周注册类型的数量,例如:
# date, count, fb_user_count, email_user_count, reg_dt
'2015-11-02', '31', '16', '15', '2015-11-02 13:59:14'
'2015-11-09', '12', '6', '6', '2015-11-09 13:59:14'
每月:
# date, count, fb_user_count, email_user_count, reg_dt
'2015-11', '131', 'x', 'y', '2015-11-02 13:59:14' (the last value is not so important)
'2015-12', '112', 'x', 'y', '2015-12-09 13:59:14'
我尝试了不同的方法,但我很难完成这项任务。任何帮助都会很棒。谢谢!
答案 0 :(得分:1)
您可以使用MySQL Date and Time functions WEEK()
,MONTH()
和YEAR()
来构建查询:
SELECT
MIN(date),
SUM(count),
SUM(fb_user_count),
SUM(email_user_count)
FROM visit
GROUP BY WEEK(date, 1); -- First day is Monday
SELECT
CONCAT(YEAR(date), '-', MONTH(date)),
SUM(count),
SUM(fb_user_count),
SUM(email_user_count)
FROM visit
GROUP BY YEAR(date), MONTH(date);
答案 1 :(得分:0)
对于您的每周报告(星期一),您可以使用
select subdate(min(date), 6-weekday(min(date))),
sum(count), sum(fb_user_count), sum(email_user_count), max(reg_dt)
from tablename
group by subdate(date, 6-weekday(date));
以及您的月度报告
select concat(year(max(date), '-', month(max(date)),
sum(count), sum(fb_user_count), sum(email_user_count), max(reg_dt)
from tablename
group by year(date), month(date);