댓글 달아주신거 보고 수정해서 다시 올립니다.
제가 원하는 부분은
(1) 년도와 상관없이 무조건 1월 1일부터 1주차여야 하고, 1월 1일부터 일주일씩 끊어 주차를 계산하고 싶습니다.
(2) 현재 달에서 다음 달으로 넘어갈 때 4일 이상인 달을 속하는 달(belong_month)로 하고 싶습니다.
(3) select 전에 set 변수를 선언해서 주차를 계산하고 있는데 변수 없이 가능할까요? |
|||||
week |
belong_month |
start_date |
end_date |
weekday_cnt |
비고 |
주차 |
속하는 달 |
시작일 |
종료일 |
요일 개수 |
|
202201 |
1 |
2022-01-01 |
2022-01-07 |
7 |
|
202202 |
1 |
2022-01-08 |
2022-01-14 |
7 |
|
202203 |
1 |
2022-01-15 |
2022-01-21 |
7 |
|
202204 |
1 |
2022-01-22 |
2022-01-28 |
7 |
|
202205 |
1 |
2022-01-29 |
2022-02-04 |
7 |
|
202206 |
2 |
2022-02-05 |
2022-02-11 |
7 |
|
202207 |
2 |
2022-02-12 |
2022-02-18 |
7 |
|
202208 |
2 |
2022-02-19 |
2022-02-25 |
7 |
|
202209 |
3 |
2022-02-26 |
2022-03-04 |
7 |
4일 이상인 달이 3월임 |
중간 생략 |
|||||
202253 |
12 |
2022-12-31 |
2022-12-31 |
1 |
|
202301 |
1 |
2023-01-01 |
2023-01-07 |
7 |
|
202302 |
1 |
2023-01-08 |
2023-01-14 |
7 |
|
202303 |
1 |
2023-01-15 |
2023-01-21 |
7 |
|
202304 |
1 |
2023-01-22 |
2023-01-28 |
7 |
|
202305 |
1 |
2023-01-29 |
2023-02-04 |
7 |
|
SET @a := 0; -- ver 1.1
SET @year := '2016-01-01';
select concat(year, lpad(week, 2, 0)) as week,
substring(start_date, 6, 2) as belong_month,
start_date,
SUBSTR( _UTF8'일월화수목금토', DAYOFWEEK(start_date), 1) as start_weekday,
end_date,
SUBSTR( _UTF8'일월화수목금토', DAYOFWEEK(end_date), 1) as end_weekday,
datediff(end_date, start_date)+1 as weekday_cnt, leap_month_yn
-- , COUNT(*) weekday_cnt
from (
select rownum, left(dt, 4) as year, dt, substring(dt, 6, 2) as tt,
case when rownum % 7 <> 0 and substring(dt, 6, 5) = '12-31' then dt
when rownum % 7 = 0 then DATE_FORMAT(DATE_SUB(`dt`, INTERVAL 6 DAY), '%Y-%m-%d') end as start_date,
case when substring(dt, 6, 5) = '12-31' then dt
when rownum % 7 = 0 then dt end as end_date,
case when rownum % 7 <> 0 and substring(dt, 6, 5) = '12-31' then @a+1
when rownum % 7 = 0 then @a := @a+1 end as week,
case when rownum = 366 and dt not like '01-01%' then 'Y' end as leap_month_yn
from
(
select row_number() over(order by dt) as rownum, dt
from
(
SELECT DATE_ADD(@year, INTERVAL seq - 1 DAY) dt,
SUBSTR( _UTF8'일월화수목금토', DAYOFWEEK(date_add(@year, interval seq - 1 day)), 1) as weekday
FROM seq_1_to_366
) a
) a
) a
where week is not null;
SELECT yw , DATE_FORMAT(mdt, '%m') m , sdt , edt , DATEDIFF(edt, sdt) + 1 cnt , SUBSTR('일월화수목금토', DAYOFWEEK(sdt), 1) sdy , SUBSTR('일월화수목금토', DAYOFWEEK(edt), 1) edy FROM (SELECT CONCAT(y, LPAD(w, 2, 0)) yw , s + INTERVAL w * 7 - 7 DAY sdt , LEAST(e, s + INTERVAL w * 7 - 4 DAY) mdt , LEAST(e, s + INTERVAL w * 7 - 1 DAY) edt FROM (SELECT y , w , CONCAT(y, '-01-01') s , CONCAT(y, '-12-31') e FROM (SELECT '2022' y, seq w FROM seq_1_to_53) a ) a ) a ;