tmp테이블에서 USER_ID가 user0001인 row를 조회하는 쿼리인데
TMP_CD 가 각각 '000002' , '000003'인 row가 존재한다면 '000003'인 row는 제외하고 조회하는 쿼리를 만들어봤는데
좀 난잡한거 같아서 더 깔끔하게 바꿀수있는 쿼리가 있는지 질문드립니다^^
SELECT A.* FROM (
SELECT
USER_ID ,
TMP_CD
(
SELECT
COUNT(1)
FROM
tmp
WHERE
USER_ID = 'user0001'
AND TMP_CD IN ('000002','000003')
) AS cnt
FROM
tmp
WHERE
USER_ID = 'user0001'
)A
WHERE (
(cnt = 2 AND TMP_CD NOT IN('000003'))
OR
(cnt < 2 AND 1=1)
);
WITH tmp AS ( SELECT 'user0001' user_id, 'A00002' tmp_cd UNION ALL SELECT 'user0001', 'B00003' UNION ALL SELECT 'user0001', '000002' UNION ALL SELECT 'user0001', '000003' ) SELECT a.* FROM tmp a LEFT OUTER JOIN tmp b ON a.user_id = b.user_id AND a.tmp_cd = '000003' AND b.tmp_cd = '000002' WHERE a.user_id = 'user0001' AND b.user_id IS NULL ;