하은양 믿음군 효실맘 호홍홍집s

PostgreSql 달력 만들기 쿼리(매달 첫주 및 마지막주 전체 포함하기) 본문

가벼운 배움/PostgreSql

PostgreSql 달력 만들기 쿼리(매달 첫주 및 마지막주 전체 포함하기)

호홍홍집 2023. 5. 9. 08:58

한번 만들어 봤슴...
달력쿼리를 찾다가 없어서 만들어 봄
매달 첫주 전체 날짜 및 마지막 주 전체 날짜가 포함되도록 짜봄.

WITH MONTH_INFO AS (
   SELECT CONCAT('202305','01')::DATE AS FIRST_DATE
   , EXTRACT(DOW FROM CONCAT('202305','01')::DATE) AS FIRST_WEEK_NUM
   , (DATE_TRUNC('MONTH', CONCAT('202305','01')::DATE) + INTERVAL '1 MONTH' - INTERVAL '1 DAY')::DATE AS LAST_DATE
   , EXTRACT(DOW FROM (DATE_TRUNC('MONTH', CONCAT('202305','01')::DATE) + INTERVAL '1 MONTH' - INTERVAL '1 DAY')::DATE) AS SECOND_WEEK_NUM 
),
CAL_INFO AS (
   SELECT A.DATES
      , TO_CHAR(A.DATES, 'YYYYMMDD') AS YMD
      , TO_CHAR(A.DATES, 'MM') AS MM
      , TO_CHAR(A.DATES, 'DD') AS DD
      , EXTRACT(DOW FROM A.DATES) AS WEEK_NUM
      , CASE WHEN A.DATES = DATE_TRUNC('DAY', NOW()) THEN 'Y' END AS IS_TODAY
      , CASE WHEN TO_CHAR(A.DATES, 'YYYYMM') = '202305' THEN 'Y' END AS IS_THIS_MONTH
   FROM (SELECT GENERATE_SERIES((DATE_TRUNC('DAY', FIRST_DATE::DATE)::DATE - FIRST_WEEK_NUM::INTEGER), (DATE_TRUNC('DAY', LAST_DATE::DATE)::DATE + SECOND_WEEK_NUM::INTEGER),'1 DAY')::DATE AS DATES 
      FROM MONTH_INFO) A
)
SELECT * FROM CAL_INFO;