안녕하세요
그룹별 경우의 수를 구하고자 하는데 애를 먹고 있어요.
경우의 수를 오라클의 경우에는 간단히 구한다는 검색결과를 보고 참고하고자 했지만
Postgre의 경우에는 간단히 가능한 방법은 없나요? 아니면 조인방법으로라도...
ID VAL
1 A
1 B
1 C
1 D
1 E
2 A
2 B
2 C
3 A
3 B
4 E
4 F
4 G
4 H
상기의 ID별 순서와 무관한 4개의 경우의 수를 구하고자 합니다. 4개의 경우의 수가 않되면 대상이 되지 않구요
경우의 수 내에서는 정렬되어 있어야하구요.
[결과표]
ID PTN
1 A-B-C-D
1 A-C-D-E
1 B-C-D-E
4 E-F-G-H
더운 날씨에 건강 유의하시길....
with t (id, val) as ( select '1', 'A' from dual union all select '1', 'B' from dual union all select '1', 'C' from dual union all select '1', 'D' from dual union all select '1', 'E' from dual union all select '2', 'A' from dual union all select '2', 'B' from dual union all select '2', 'C' from dual ) , t2(id, val, path, lv, cnt) as ( select id, val, cast(val as varchar2(4000)) , 1 , count(1) over(partition by id) cnt from t union all select t.id, t.val, t2.path||'-'||t.val , lv + 1 , cnt from t, t2 where instr(t2.path,t.val) = 0 and t.id = t2.id ) select path from ( select path, row_number() over(partition by id order by path) rn ,count(1) over(partition by id) totcnt from t2 where cnt = lv ) where rn <= 4 and totcnt >= 4
심심해서 oracle로 작성해봤는데..
비효율적이네요. 검색해보니
postgre도 with recursive 문으로 재귀 쿼리 가능한 거 같네요.