遵循模式的自定义日历

时间:2019-06-20 16:47:31

标签: mysql calendar

我需要创建一个自定义日历,其中同时包含期间和销售/非销售期间:

  • 期间的模式为4周,4周,5周,4周,4周,5周,并反复重复。

  • 销售的模式为9周销售和4周非销售,并且这种情况也一遍又一遍地重复。

尽管我不知道该如何实现,但是如果我需要在Excel上创建日历,那么构建5年的日历将非常烦人(而且我讨厌Excel)。请帮忙!!!

我已经成功地通过使用笛卡尔联接获得了周数等,并且还获得了正确的周数。到目前为止,我可以做的是:

SET @row_number = 0;

SELECT *,

DAYNAME(gen_date) as day_of_week,

YEAR(gen_date) as calendar_year,

'2019/2020' as calendar_period,

FLOOR(1 + ((number) -1) / 7) as Week_number,

FLOOR(1 + ((number) -1) / 91) as Quarter,

gen_date - INTERVAL (WEEKDAY(gen_date)) DAY AS week_commencing_start,

gen_date - INTERVAL (WEEKDAY(gen_date)-6) DAY AS week_commencing_end

FROM


(select * from 
(select (@row_number:=@row_number + 1) number, adddate('2019-04-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) gen_date



from
 (select 0 t0 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 t1 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 t2 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 t3 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 t4 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 gen_date between '2019-04-01' and '2020-03-29') b;

如果有人要检查模式,请查看此Excel文件:

https://drive.google.com/file/d/1yWUWEkCoCXau5kST18rI2YOWMW4sxQUC/view?usp=sharing

谢谢大家!

1 个答案:

答案 0 :(得分:0)

我认为,这将为您提供想要的东西。

set @startdate = '2019-04-01';
set @weekoffset = WEEK(@startDate) -1 ;

WITH RECURSIVE weeks(wk, wkn, auxperiod, period, sales) AS 
(
  select @startDate , WEEK(@startDate) + CASE WHEN WEEK(@startDate) - @weekoffset > 0 THEN -@weekoffset ELSE 52 - @weekoffset end, 1, 1, 'S'
  UNION ALL 
  select DATE_ADD(wk, INTERVAL 1 WEEK), 
        WEEK(DATE_ADD(wk, INTERVAL 1 WEEK)) + CASE WHEN WEEK(DATE_ADD(wk, INTERVAL 1 WEEK)) - @weekoffset > 0 THEN -@weekoffset ELSE 52 - @weekoffset end, 
       case when auxperiod + 1 > 13 then 1 else auxperiod + 1 end, 
       case when auxperiod + 1 = 5 or auxperiod + 1 = 9 or auxperiod + 1 = 14 then period + 1 else period end, 
       case when auxperiod + 1 < 10 or auxperiod + 1 > 13 then 'S' else 'N' end
    FROM weeks 
    WHERE wk < DATE_ADD(@startdate, INTERVAL 5 Year) -- end date - add 5 years to startdate
)
select * FROM weeks

生成的表将包含列:

  • wk(星期开始日期)
  • wkn(根据开始日期的星期数)
  • 辅助句(辅助列仅用于计算)
  • 期间(期间号)
  • 销售(销售周的值为“ S”,非销售周的值为“ N”)