在MySQL中将Month转换为周

时间:2018-09-10 22:19:09

标签: mysql

我希望在MySQL中将一个月分解成几个星期(从星期一开始)。

例如

 Sept 3 - 9th 

 Sept 10 - 16th

如何使用MySql实现此目的?

谢谢。

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

此查询将产生所需的结果。它使用Currency生成一个月(0到4)中可能的星期数的表,然后将这些星期数添加到该月的第一个星期一的计算中(存储在变量@firstday中,加入周数表。

UNION

输出:

SELECT @firstday + INTERVAL w WEEK AS start, @firstday + INTERVAL w WEEK + INTERVAL 6 DAY AS end 
FROM (SELECT 0 AS w UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) weeks
JOIN (SELECT @firstday := FROM_DAYS(TO_DAYS(CURDATE())-DAY(CURDATE())+1) +
                          (7 - WEEKDAY(FROM_DAYS(TO_DAYS(CURDATE())-DAY(CURDATE())+1))) % 7) f
HAVING end <= LAST_DAY(@firstday)

要运行任意给定月份的查询,请将start end 2018-09-03 2018-09-09 2018-09-10 2018-09-16 2018-09-17 2018-09-23 2018-09-24 2018-09-30 (4个地方)的计算中的CURDATE()替换为您感兴趣的月份中的日期,例如

@firstday

输出:

SELECT @firstday + INTERVAL w WEEK AS start, @firstday + INTERVAL w WEEK + INTERVAL 6 DAY AS end 
FROM (SELECT 0 AS w UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) weeks
JOIN (SELECT @firstday := FROM_DAYS(TO_DAYS('2018-01-20')-DAY('2018-01-20')+1) +
                          (7 - WEEKDAY(FROM_DAYS(TO_DAYS('2018-01-20')-DAY('2018-01-20')+1))) % 7) f
HAVING end <= LAST_DAY(@firstday)

如果您可以灵活设置变量,则可以像这样清理查询:

start       end     
2018-01-01  2018-01-07
2018-01-08  2018-01-14
2018-01-15  2018-01-21
2018-01-22  2018-01-28