일단 확인하시기 편하게 WITH 문을 이용하여 기본 데이터를 만들어 보았습니다.
WITH TB_SAMPLE AS ( SELECT TO_CHAR(SYSDATE - 1 , 'YYYYMMDD') AS SAMPLE_DT, 'H' AS SAMPLE_TYPE, '책상' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 2 , 'YYYYMMDD') AS SAMPLE_DT, 'H' AS SAMPLE_TYPE, '책상' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 1 , 'YYYYMMDD') AS SAMPLE_DT, 'Z' AS SAMPLE_TYPE, '칠판' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 3 , 'YYYYMMDD') AS SAMPLE_DT, 'H' AS SAMPLE_TYPE, '의자' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 6 , 'YYYYMMDD') AS SAMPLE_DT, 'A' AS SAMPLE_TYPE, '학생' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 3 , 'YYYYMMDD') AS SAMPLE_DT, 'A' AS SAMPLE_TYPE, '선생' AS SAMPLE_NAME FROM DUAL ) SELECT * FROM TB_SAMPLE
위 쿼리 문을 복사하셔서 sql 창에 붙여넣고 돌리시면 아래와 같이 데이터가 조회 됩니다.
SAMPLE_DT SAMPLE_TYPE SAMPLE_NAME
20141026 H 책상
20141025 H 책상
20141026 Z 칠판
20141024 H 의자
20141021 A 학생
20141024 A 선생
이 데이터 중에 SAMPLE_TYPE 값이 'H' 인 행의 수를 구하려고 합니다.
현재 SUM 과 DECODE 이용하여 행의 수를 구해 보았습니다.
WITH TB_SAMPLE AS ( SELECT TO_CHAR(SYSDATE - 1 , 'YYYYMMDD') AS SAMPLE_DT, 'H' AS SAMPLE_TYPE, '책상' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 2 , 'YYYYMMDD') AS SAMPLE_DT, 'H' AS SAMPLE_TYPE, '책상' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 1 , 'YYYYMMDD') AS SAMPLE_DT, 'Z' AS SAMPLE_TYPE, '칠판' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 3 , 'YYYYMMDD') AS SAMPLE_DT, 'H' AS SAMPLE_TYPE, '의자' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 6 , 'YYYYMMDD') AS SAMPLE_DT, 'A' AS SAMPLE_TYPE, '학생' AS SAMPLE_NAME FROM DUAL UNION ALL SELECT TO_CHAR(SYSDATE - 3 , 'YYYYMMDD') AS SAMPLE_DT, 'A' AS SAMPLE_TYPE, '선생' AS SAMPLE_NAME FROM DUAL ) SELECT SUM(DECODE(SAMPLE_TYPE, 'H', 1, 0)) AS SAMPLE_SUM FROM TB_SAMPLE
이렇게 작성하여 조회하게 되면 SAMPLE_SUM 의 값이 3이 나옵니다.
여기서 추가적으로 SAMPLE_TYPE 값이 'H' 이고
SAMPLE_NAME 중복이라면 중복된 값을 1로 처리하여 조회하고 싶습니다.
20141026 H 책상 <--중복
20141025 H 책상 <--중복
20141024 H 의자
SAMPLE_TYPE 값이 H 인것만 조회하면 3건이지만
SAMPLE_NAME 값이 중복건이 있어 이 중복건을 한건으로 처리하여
총 행의수가 2가 나왔으면 합니다....
굉장히 쉬울것 같은데....잘 안풀리네요 ㅠㅠ 답변 부탁 드리겠습니다.
SELECT COUNT(DISTINCT sample_name) cnt FROM tb_sample WHERE sample_type = 'H'