我需要做我认为简单的SQL查询...但我决定如何将它们分组:
<p>I've got the below table:</p>
Company | Airport | Type
------------------------------------------
SP1 | AP1 | ST1
SP1 | AP1 | ST2
SP1 | AP1 | ST3
SP1 | AP2 | ST1
SP1 | AP2 | ST2
SP1 | AP2 | ST3
SP1 | AP3 | ST1
SP1 | AP3 | ST2
SP1 | AP4 | ST1
SP1 | AP4 | ST2
SP1 | AP4 | ST3
SP1 | AP4 | ST4
我希望按以下方式对AP
和ST
进行分组,以便所需的结果如下:
(案例1)
SP | AP | ST
------------------------------------------
SP1 | AP1, AP2, AP4 | ST1, ST2, ST3
SP1 | AP3 | ST1, ST2
SP1 | AP4 | ST4
有什么想法?真的很感激!
更新
正如所指出的,结果还有另一种选择:
(案例2)
SP | AP | ST
------------------------------------------
SP1 | AP1, AP2 | ST1, ST2, ST3
SP1 | AP3 | ST1, ST2
SP1 | AP4 | ST1, ST2, ST3, ST4
我还在列中添加了标题以提供更多上下文。这个想法只是为了能够对相关元素进行分组。我对这两个结果中的任何一个都感到满意,如果可能的话,我希望这两个结果都是......
答案 0 :(得分:0)
没有描述为什么AP4 / ST4是一个特殊情况,但假设你试图在ST中为每个(sp,ap)分组3个连续元素:
SQL> with t (SP, AP, ST) as (
2 select 'SP1','AP1','ST1' from dual union all
3 select 'SP1','AP1','ST2' from dual union all
4 select 'SP1','AP1','ST3' from dual union all
5 select 'SP1','AP2','ST1' from dual union all
6 select 'SP1','AP2','ST2' from dual union all
7 select 'SP1','AP2','ST3' from dual union all
8 select 'SP1','AP3','ST1' from dual union all
9 select 'SP1','AP3','ST2' from dual union all
10 select 'SP1','AP4','ST1' from dual union all
11 select 'SP1','AP4','ST2' from dual union all
12 select 'SP1','AP4','ST3' from dual union all
13 select 'SP1','AP4','ST4' from dual
14 )
15 select sp, listagg(ap,',') within group (order by ap) lstap, lstst
16 from (
17 select sp, ap, listagg(st,',') within group (order by st) lstst from (
18 select sp, ap, st, ceil((row_number() over(partition by sp, ap order by st))/3) grp
19 from t
20 )
21 group by sp, ap, grp
22 )
23 group by sp, lstst
24 order by 1,2,3
25 /
SP LSTAP LSTST
--- ------------------------- -------------------------
SP1 AP1,AP2,AP4 ST1,ST2,ST3
SP1 AP3 ST1,ST2
SP1 AP4 ST4
P.S。对于替代结果输出:
SQL> with t (SP, AP, ST) as (
2 select 'SP1','AP1','ST1' from dual union all
3 select 'SP1','AP1','ST2' from dual union all
4 select 'SP1','AP1','ST3' from dual union all
5 select 'SP1','AP2','ST1' from dual union all
6 select 'SP1','AP2','ST2' from dual union all
7 select 'SP1','AP2','ST3' from dual union all
8 select 'SP1','AP3','ST1' from dual union all
9 select 'SP1','AP3','ST2' from dual union all
10 select 'SP1','AP4','ST1' from dual union all
11 select 'SP1','AP4','ST2' from dual union all
12 select 'SP1','AP4','ST3' from dual union all
13 select 'SP1','AP4','ST4' from dual
14 )
15 select sp, listagg(ap,',') within group (order by ap) lstap, lstst
16 from (
17 select sp, ap, listagg(st,',') within group (order by st) lstst from (
18 select sp, ap, st
19 from t
20 )
21 group by sp, ap
22 )
23 group by sp, lstst
24 order by 1,2,3
25 /
SP LSTAP LSTST
--- ------------------------- -------------------------
SP1 AP1,AP2 ST1,ST2,ST3
SP1 AP3 ST1,ST2
SP1 AP4 ST1,ST2,ST3,ST4