programing

MariaDB 주 시작 날짜 & 주 번호 1 ~ 52

mailnote 2023. 7. 25. 21:12
반응형

MariaDB 주 시작 날짜 & 주 번호 1 ~ 52

날짜에서 주를 가져오기 위해 저장 프로시저를 작성했는데, 주 시작 날짜와 주 번호, 연도도 함께 반환됩니다.

저는 'WEEK' 기능을 알고 있지만, 이것은 저에게 요일을 알려주지 않고, 주와 연도를 지정하여 이 기능을 수행하는 기능을 알지 못합니다.

질문:
주 번호가 주어진 주의 시작 날짜는 어떻게 알 수 있습니까?요일 인덱스로 주의 시작을 전달하는 경우, 0 = 일요일, 1 = 월요일 등입니다.

제 현재 기능이 항상 작동하는 것은 아니며, 만약 한 주의 첫 날이 월요일이라면, 일요일은 제가 원하는 것과 같은 주의 끝이 아니라 다음 주로 넘어갑니다.

저도 이것에 대해 좀 캐고 있었어요.하지만 저는 작동하는 mysql 코드를 우연히 발견했습니다.기본적으로 요일을 기준으로 날짜를 뺍니다. 즉, 날짜가 Wed(4)인 경우 날짜가 1-4=-3일 전이라는 것을 알 수 있습니다.

이거 어때:

# with Sunday being the start of the week:
select convert(date_add(now(), interval(1-dayofweek(now())) day), date) as WeekStartDate
select convert(date_add(now(), interval(7-dayofweek(now())) day), date) as WeekEndDate

# with Monday being the start of the week:
select convert(date_add(now(), interval(2-dayofweek(now())) day), date) as WeekStartDate
select convert(date_add(now(), interval(8-dayofweek(now())) day), date) as WeekEndDate

신용: mysql에서 날짜의 번째 요일을 얻으려면 어떻게 해야 합니까?

Sequence 엔진을 사용합니다.필요에 따라 다음 예제를 조정할 수 있습니다.

MariaDB [_]> SHOW ENGINES\G
.
.
.
*************************** 3. row ***************************
      Engine: SEQUENCE
     Support: YES
     Comment: Generated tables filled with sequential values
Transactions: YES
          XA: NO
  Savepoints: YES
.
.
.

MariaDB [_]> SET @`year` := 2016,
          ->     @`mode` := 1,
          ->     @`week` := 23;
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> SELECT
          ->   `der`.`date`,
          ->   `der`.`week`,
          ->   `der`.`year`
          -> FROM (
          ->   SELECT
          ->     `der`.`date`,
          ->     WEEK(`der`.`date`, @`mode`) `week`,
          ->     YEAR(`der`.`date`) `year`
          ->   FROM (
          ->     SELECT
          ->       DATE_ADD(CONCAT(@`year`, '-01-01'), INTERVAL `s`.`seq` DAY) `date`
          ->     FROM
          ->       seq_0_to_365 `s`
          ->   ) `der`
          -> ) `der`
          -> WHERE
          ->   `der`.`week` = @`week` AND
          ->   `der`.`year` = @`year`;
+------------+------+------+
| date       | week | year |
+------------+------+------+
| 2016-06-06 |   23 | 2016 |
| 2016-06-07 |   23 | 2016 |
| 2016-06-08 |   23 | 2016 |
| 2016-06-09 |   23 | 2016 |
| 2016-06-10 |   23 | 2016 |
| 2016-06-11 |   23 | 2016 |
| 2016-06-12 |   23 | 2016 |
+------------+------+------+
7 rows in set (0.01 sec)

해결됨, 저장 프로시저를 다시 작성했습니다.

    exitProc:BEGIN
    #--
    # Procedure:
    #   weekFromDate
    #
    # Parameters:
    #   vcCompKey, the key associated with the company
    #   dtDate, the date to translate
    #   dtOutSOW, returned start of week date
    #   siOutWeek, returned week number
    #   siOutYear, returned year
    #--
        DECLARE siDIY          SMALLINT;   #Day in year
        DECLARE siFDOW         SMALLINT;   #First day of week
        DECLARE siGoBack       SMALLINT;      #Flag used to check for last year
        DECLARE siRmonth       SMALLINT;   #Reference Month
        DECLARE siRyear        SMALLINT;   #Reference Year
        DECLARE dtSOY          DATE;       #Date of start of year
        DECLARE vcFMDOY        VARCHAR(12);#First month and day of year
        DECLARE vcFDOW         VARCHAR(12);#First day of the week
        DECLARE vcDYSOW        VARCHAR(80);#Days of week
    #Get the first day of the week for the specified company
        SET vcFDOW = vcGetParamValue(vcCompKey, 'Var:First day of week');

    IF (vcFDOW IS NULL) THEN
    #No entry found, abort! 
        LEAVE exitProc;
    END IF;
    #Get the first month and day of the year for the specified company
    SET vcFMDOY = vcGetParamValue(vcCompKey, 'Var:First day of year');  

    IF (vcFMDOY IS NULL) THEN
    #No entry found, abort! 
        LEAVE exitProc;
    END IF;
    #Set-up days of week
    SET vcDYSOW = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday';   
    #Get the first day of the week index base 1
    SET siFDOW = FIND_IN_SET(LOWER(vcFDOW), LOWER(vcDYSOW)) - 1;
    #Get the reference month and year   
    SET siRmonth = MONTH(dtDate);
    SET siRyear = YEAR(dtDate);
    SET dtSOY = DATE(CONCAT(siRyear, '/', vcFMDOY)); 
    #Calculate the start of week date
    SET dtOutSOW = DATE_SUB(dtDate, INTERVAL (DAYOFWEEK(dtDate) - siFDOW) DAY) + 1;
    #Calculate the day in year
    SET siDIY = DATEDIFF(dtOutSOW, dtSOY);
    #Do we need to go back to the end of the previous year? 
    SET siGoBack = YEAR(dtDate) - YEAR(dtOutSOW);

    IF siGoBack < 0 Or siDIY < 0 Or dtDate < dtOutSOW THEN
    #Yes
        IF YEAR(dtOutSOW) = YEAR(dtDate) THEN
            SET dtOutSOW = DATE_SUB(dtOutSOW, INTERVAL 7 DAY);
        END IF;
        SET dtSOY = DATE(CONCAT(YEAR(dtOutSOW), '/', vcFMDOY)); 
        SET siDIY = DATEDIFF(dtOutSOW, dtSOY);
    END IF;     
    #Calculate the week no. and year
    SET siOutWeek = (siDIY / 7) + 1;
    SET siOutYear = YEAR(dtOutSOW); 
END

이 루틴에서는 데이터베이스의 다른 테이블을 사용하고 회사의 연도 시작을 다르게 할 수 있습니다.

테스트를 위해 이번 주의 시작을 찾겠습니다. 첫 번째 참고 사항:

mysql> SELECT NOW(), WEEK(NOW());
+---------------------+-------------+
| NOW()               | WEEK(NOW()) |
+---------------------+-------------+
| 2016-06-18 12:10:58 |          24 |
+---------------------+-------------+

다음은 함수의 고기입니다.

mysql> SELECT '2016-01-01'
             + INTERVAL 7*24
             - DAYOFWEEK('2016-01-01')
             + 1 DAY;
+----------------------------------------------------------------+
| '2016-01-01' + INTERVAL 7*24 - DAYOFWEEK('2016-01-01') + 1 DAY |
+----------------------------------------------------------------+
| 2016-06-12                                                     |
+----------------------------------------------------------------+

'2016-01-01'문제의 한 해의 시작입니다.
24그것은WEEK()번호.
+ 1 DAY한 주의 시작을 보상하는 것입니다.
일주일이 시작되는 요일에 대한 선택사항을 처리하기 위해 다른 작업을 수행해야 합니다.

사용자 1014010의 답변에 대한 일부 수정.한 주가 월요일로 시작하면 다음 주 일요일 날짜가 표시됩니다.제 수정 사항이 있습니다.

SELECT DATE(DATE_ADD(NOW(), INTERVAL -((5 + DAYOFWEEK(NOW())) % 7) DAY)) AS WeekStartDate

언급URL : https://stackoverflow.com/questions/37687671/mariadb-start-of-week-date-week-number-1-to-52

반응형