我很确定这是可能的,但我不太清楚如何。
请考虑以下表格:
A B C
1 1 A
1 2 A
1 2 B
2 1 C
2 2 A
2 2 B
2 2 C
我想将其呈现为:
A B C
1 1 A
1 2 A
B
2 1 C
2 2 A
B
C
换句话说,分组在唯一(A,B)上。 我正在考虑 GROUP BY ROLLUP ,但我无法弄清楚如何在没有按功能分组的情况下使行无效。 (注意:我想以前曾经问过这个问题,但我找不到合适的搜索条件来找到它。谢谢)
答案 0 :(得分:4)
试试这个:
create table t
(a number,
b number,
c varchar2(1));
insert into t values(1, 1, 'A');
insert into t values(1, 2, 'A');
insert into t values(1, 2, 'B');
insert into t values(2, 1, 'C');
insert into t values(2, 2, 'A');
insert into t values(2, 2, 'B');
insert into t values(2, 2, 'C');
select case when rn = 1
then a
else null end as a,
case when rn = 1
then b
else null end as b,
c
from (select a, b, c,
row_number() over (partition by a, b order by c) as rn,
row_number() over (order by a, b, c) as rn_total
from t)
order by rn_total;
A B C
- - -
1 1 A
1 2 A
B
2 1 C
2 2 A
B
C
最后,清理您的测试环境:
drop table t purge;
即使没有子查询,您也可以这样做:
select case when row_number() over (partition by a, b order by c) = 1
then a
else null end as a,
case when row_number() over (partition by a, b order by c) = 1
then b
else null end as b,
c
from t
order by t.a, t.b, c ;
进行测试