간단한 쿼리인데 제가 실력이 부족해서 제가 원하는 결과값이 도출이 안되네요
고수님들 혹시 해결이 가능할까요?
쿼리문 예시
SELECT CASE WHEN 날짜 = '20230304' THEN '20230304'
WHEN 날짜 BETWEEN '20230101' AND '20230331' THEN '2023.01.01~2023.03.31'
WHEN 날짜 BETWEEN '20230101' AND '20231231' THEN '2023.01.01~2023.12.31'
END 구분,
COUNT(*)
FROM
(
SELECT 날짜, 값 FROM 테이블
WHERE 1=1
AND 날짜 BETWEEN '20230101' AND '20231231'
)
GROUP BY CASE WHEN 날짜 = '20230304' THEN '20230304'
WHEN 날짜 BETWEEN '20230101' AND '20230331' THEN '2023.01.01~2023.03.31'
WHEN 날짜 BETWEEN '20230101' AND '20231231' THEN '2023.01.01~2023.12.31'
END
내가 원하는 결과값
날짜 | 결과값 |
2022.1.2~12.31 | 1,000 |
2022.1.2~03.31 | 200 |
2022.03.04 | 10 |
실제 쿼리 결과값
날짜 | 결과값 |
2022.1.2~12.31 | 800 |
2022.1.2~03.31 | 190 |
2022.03.04 | 10 |
WITH t AS ( SELECT '20220304' dt, 10 v FROM dual UNION ALL SELECT '20220305', 190 FROM dual UNION ALL SELECT '20220401', 800 FROM dual ) SELECT a.sdt || DECODE(a.sdt, a.edt, '', '~'||a.edt) gb , SUM(b.v) v FROM (SELECT 1 no, '20220101' sdt, '20221231' edt FROM dual UNION ALL SELECT 2, '20220101', '20220331' FROM dual UNION ALL SELECT 3, '20220304', '20220304' FROM dual ) a LEFT OUTER JOIN t b ON b.dt BETWEEN a.sdt AND a.edt GROUP BY a.no, a.sdt, a.edt ORDER BY a.no ;