by 게릴라 [SQLServer] mssql sum union [2022.02.09 11:38:20]
안녕하세요.
아래와 같은 쿼리를 작성했는데 sum해야할 대상 컬럼의 조회조건이 각각 달라서 union all 로 처리했습니다.
SELECT SUM(A_CNT) ,
SUM(B_CNT),
SUM(C_CNT)
FROM (
SELECT COUNT(SEQ) AS A_CNT,
0 AS B_CNT,
0 AS C_CNT
FROM TARGET_TABLE WITH(NOLOCK)
WHERE REG_DT BETWEEN '조회시작일' AND '조회종료일' AND CONDITION_ID = 'A'
UNION ALL
SELECT 0 AS A_CNT,
COUNT(SEQ) AS B_CNT,
0 AS C_CNT
FROM TARGET_TABLE WITH(NOLOCK)
WHERE REG_DT BETWEEN '조회시작일' AND '조회종료일' AND CONDITION_VAL > 0
UNION ALL
SELECT 0 AS A_CNT,
0 AS B_CNT,
COUNT(SEQ) AS C_CNT
FROM TARGET_TABLE WITH(NOLOCK)
WHERE REG_DT BETWEEN '조회시작일' AND '조회종료일' AND CONDITION_TYPE = 'O'
)
*조회조건 REG_DT에 클러스터드 index
이 쿼리를 수정하여 성능을 개선하고 싶은데 sum over partition by 구문으로 변경이 가능할까요.
오라클이면
select
count(distinct case when CONDITION_ID = 'A' then SEQ end) over (partition by SEQ) as A_CNT,
count(distinct case when CONDITION_VAL > 0 then SEQ end) over (partition by SEQ) as B_CNT,
count(distinct case whenCONDITION_TYPE = 'O' then SEQ end) over (partition by SEQ) as C_CNT
같은 형태로 가능할 거 같은데 mssql에선 오류가 나서...
좋은 방법이 없을까요?
긴 글 읽어주셔서 감사합니다.
고견 부탁드립니다.