列出两个日期之间所有周的存储过程

时间:2015-02-17 21:08:52

标签: mysql date

我已经搜索过,但找不到如何在两个日期之间列出周数的解决方案。

我找到的解决方案列出了两个日期之间的所有日期:

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 '2012-02-10' and '2012-02-15'

但没有任何内容列出星期为7天的周格式,如下:

你会怎么做?

周开始时间:2015-02-01 - 周末:2015-02-07

周开始时间:2015-02-08 - 周末:2015-02-14

周开始时间:2015-02-15 - 周末:2015-02-21

周开始时间:2015-02-22 - 周末:2015-02-28

1 个答案:

答案 0 :(得分:1)

您可以选择所有日期并在一周的第一天(date_format(selected_date, '%w') = 0)过滤:

select selected_date, date_add(selected_date, INTERVAL 6 DAY)
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 '2015-02-01' and '2015-02-28'
  AND date_format(selected_date, '%w') = 0

SQLFIDDLE:http://sqlfiddle.com/#!2/7bc0e/52

您可以使用

AND DAYOFWEEK(selected_date) = 1

而不是

date_format(selected_date, '%w') = 0

我认为它更具可读性:http://sqlfiddle.com/#!2/7bc0e/54