no | code |
1 | annan |
2 | nanae |
3 | annen |
4 | nnann |
5 | aannn |
6 | nnaan |
tb_l : AAA
AAA 테이블에 code 라는 컬럼이 위와 같이 있습니다.
얻고자 하는값은 다음과 같습니다.
코드값은 5자리 입니다. ㅁㅁㅁㅁㅁ
1) 맨 앞자리에 a가 몇개, n이 몇개, e가 몇개 인가?
2) 두번째 자리에 a가 몇개, n이 몇개, e가 몇개 인가?
이런식으로 5번째 자리까지 각각의 갯수를 알고자 합니다.
위의 표를 기준으로 최종적으로 얻게 되는 값은 이렇습니다.
$1a = 3; $2a = 2; $3a = 2; $4a = 3; $5a = 0;
$1n = 3; $1n = 4; $3n = 4; $4n = 2; $5n = 5;
$1e = 0; $1e = 0; $3e = 0; $4e = 1; $5e = 1;
어떻게 구현을 하면 될까요...
만들고보니... decode를 쓰셔도 될 것 같습니다.
with t as ( select 1 no, 'annan' code from dual union all select 2, 'nanae' from dual union all select 3, 'annen' from dual union all select 4, 'nnann' from dual union all select 5, 'aannn' from dual union all select 6, 'nnaan' from dual ), tmp as ( select 'a' c1 from dual union all select 'n' from dual union all select 'e' from dual ) select c1, sum(v1), sum(v2), sum(v3), sum(v4), sum(v5) from ( select c1, case when substr(code,1,1)=c1 then 1 else 0 end v1, case when substr(code,2,1)=c1 then 1 else 0 end v2, case when substr(code,3,1)=c1 then 1 else 0 end v3, case when substr(code,4,1)=c1 then 1 else 0 end v4, case when substr(code,5,1)=c1 then 1 else 0 end v5 from t, tmp ) group by c1
WITH t AS ( SELECT 1 no, 'annan' code FROM dual UNION ALL SELECT 2, 'nanae' FROM dual UNION ALL SELECT 3, 'annen' FROM dual UNION ALL SELECT 4, 'nnann' FROM dual UNION ALL SELECT 5, 'aannn' FROM dual UNION ALL SELECT 6, 'nnaan' FROM dual ) SELECT * FROM (SELECT lv , SUBSTR(code, lv, 1) cd FROM t , (SELECT LEVEL lv FROM dual CONNECT BY LEVEL <= 5) ) PIVOT (COUNT(*) FOR lv IN (1, 2, 3, 4, 5)) ;