[英]mysql - select count multiple tables, group by week, custom date range
For example, I have 2 tables and a date range (1 dec 2015 - 10 jan 2016). 例如,我有2个表和一个日期范围(2015年12月1日至2016年1月10日)。
First table: USERS 第一张桌子:USERS
id (int) date (datetime)
1 3-dec-2015
2 4-dec-2015
3 19-dec-2015
4 20-dec-2015
5 21-dec-2015
6 29-dec-2015
7 30-dec-2015
Second table: BIRTHDAYS 第二张桌子:BIRTHDAYS
id (int) date (datetime)
1 6-dec-2015
2 8-dec-2015
3 9-dec-2015
4 17-dec-2015
5 28-dec-2015
The result after the query should be the following: 查询后的结果应为以下内容:
[0] 1st week => 2 users, 1 birthday
[1] 2nd week => 0 users, 2 birthday
[2] 3ed week => 1 users, 1 birthday
[3] 4th week => 1 users, 0 birthday
[4] 5th week => 2 users, 1 birthday
[5] 6th week => 0 users, 0 birthday
Any ideas how to achive this result or something close? 任何想法如何达到这个结果或接近? I can use and PHP if needed. 如果需要,我可以使用和PHP。
I would start off with something like this: 我将从以下内容开始:
select ((week(dateb) - week('2015-12-01')) + 1) as week_number, count(a.dateb) as userdates
from users as a
where dateb between '2015-12-01' and '2016-01-01'
group by week(dateb)
order by week(dateb);
and 和
select ((week(dateb2) - week('2015-12-01')) + 1) as week_number, count(dateb2) as birthdays
from birthdays
where dateb2 between '2015-12-01' and '2016-01-01'
group by week(dateb2)
order by week(dateb2);
Demo, http://sqlfiddle.com/#!9/c83cb/21 演示, http: //sqlfiddle.com/#!9 / c83cb / 21
from there you can fiddle with the outputting with PHP. 从那里,您可以摆弄PHP的输出。
Also note with this approach only rows with populated data are returned. 还要注意,使用这种方法只会返回包含填充数据的行。 So you should check on the iteration that each row is incremented by 1. 因此,您应该检查迭代过程,以确保每行都增加1。
eg so for users
when you got from week 1 to week 3 you should output week 2 = 0
; 例如,对于users
当您从第1周到第3周时,应该输出week 2 = 0
; or however you want to display it. 或者您想显示它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.