获取给定日期范围的周并获取数周的数据(MYSQL)

时间:2017-07-14 10:47:58

标签: php mysql

我需要一个查询,列出给定日期范围的周数,并且必须从日历计算周数,而不是从表格中的任何列计算。然后在一周的日期中,我需要得到周的ID总数。我使用此查询来获取周数

select * from (select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v 
where selected_date between '2017-04-13' and '2017-07-12' group by WEEK(ADDDATE(selected_date,1)) order by selected_date asc

然后使用日期范围,我会获得每周的ID总数,如果一周内没有ID ,那么我将得到的计数为0在查询下面

SELECT sum1, sum2 FROM 
(SELECT count(id) AS sum1 FROM vqn_list 
WHERE ( sl_posted_date BETWEEN ( '2017-05-01' ) AND ( '2017-05-10' ) )) AS T1 
JOIN (SELECT count(id) AS sum2 FROM vqn_list
 WHERE ( sl_posted_date BETWEEN ( '2017-05-11' ) AND ( '2017-05-20' ) )) AS T2

表格结构:

| id        | sl_posted_date
-------------------------------
| 1         | 2017-05-01
| 2         | 2017-05-03
| 3         | 2017-05-04
| 4         | 2017-05-06
| 5         | 2017-05-08
| 6         | 2017-05-015
...

我需要将结果作为:

| selected_date          | counts
-----------------------------------
| 2017-04-8              | 45
| 2017-04-15             | 65
| 2017-04-22             | 489
| 2017-04-29             | 7852
| 2017-05-06             | 50

日期范围的查询非常大。是否可以将两个查询加入一个?我有一个像200万的数据,像3年,所以第二个查询是如此缓慢。请帮助我加入查询,因为我在MYSQL查询中不太好。

0 个答案:

没有答案