반응형
일별통계 쿼리 작성시 데이터가 없어 데이터가 빠지는 현상이 있다.
이럴땐 spt_values 을 활용하여 LEFT OUTER JOIN 을 걸어 데이터 추출이 가능하다
DECLARE @S_DATE smalldatetime,@E_DATE smalldatetime
SET @S_DATE = CONVERT(smalldatetime, '2019-02-01') -- 특정월 시작일자
SET @E_DATE = DATEADD(day, -1,DATEADD(MONTH, 1,DATENAME(YEAR,@S_DATE) + DATENAME(month,@S_DATE)+'01')) -- 특정월 종료일자
SELECT CONVERT(CHAR(10), DATEADD(d, NUMBER, @S_DATE),120) AS DT
FROM MASTER..SPT_VALUES WITH(NOLOCK)
WHERE TYPE = 'P' AND CONVERT(CHAR(10), DATEADD(D, NUMBER, @S_DATE), 120) <= @E_DATE
LEFT OUTER JOIN 으로 일별 통계 쿼리 작성
-- 일별 GROUP BY
DECLARE @S_DATE smalldatetime,@E_DATE smalldatetime
SET @S_DATE = CONVERT(smalldatetime, CONCAT(@regDate , '-01'))
SET @E_DATE = DATEADD(day, -1,DATEADD(MONTH, 1,DATENAME(YEAR,@S_DATE) + DATENAME(month,@S_DATE)+'01')) -- 특정월 종료일자
SELECT DT.DT AS regDate
, ISNULL(SUM(openCnt),0) AS openCnt
, ISNULL(SUM(chargeCnt),0) AS chargeCnt
, ISNULL(SUM(freeCnt),0) AS freeCnt
, ISNULL(SUM(openAmount),0) AS openAmount
, ISNULL(SUM(chargeAmount),0) AS chargeAmount
, ISNULL(SUM(voiceAmount),0) AS voiceAmount
, ISNULL(SUM(etcAmount),0) AS etcAmount
, ISNULL(SUM(freeAmount),0) AS freeAmount
, ISNULL(SUM(etcAmount),0) AS etcAmount
, ISNULL(SUM(turnDiscount),0) AS turnDiscount
, ISNULL(SUM(autoDiscount),0) AS autoDiscount
, ISNULL(SUM(promotionDiscount),0) AS promotionDiscount
, ISNULL(SUM(totalAmount),0) AS totalAmount
FROM (
SELECT CONVERT(CHAR(10), DATEADD(d, NUMBER, @S_DATE),120) AS DT
FROM MASTER..SPT_VALUES WITH(NOLOCK)
WHERE TYPE = 'P' AND CONVERT(CHAR(10), DATEADD(D, NUMBER, @S_DATE), 120) <= @E_DATE
) AS DT
LEFT OUTER JOIN #tbl AS tbl
ON DT.DT = tbl.regDate
GROUP BY DT.DT
ORDER BY DT.DT ASC
728x90
반응형
'DataBase > MSSQL' 카테고리의 다른 글
[MSSQL] INDEX 파편화 확인 인덱스 리빌드를 통한 성능 최적화 (3) | 2024.09.06 |
---|---|
[MSSQL] SP 문자열이나 이진데이터가 잘립니다. (0) | 2021.11.25 |
[MSSQL] ROW 를 컬럼으로 바꾸는 방식 (PIVOT 과 CASE문) (0) | 2021.11.24 |
[MSSQL] 두테이블간 교집합(INTERSECT) 차집합(EXCEPT) 찾기 (0) | 2021.11.22 |
[MSSQL]MSSQL 날짜 변환표(GETDATE, CONVERT) (0) | 2021.11.09 |