在Oracle中,我遇到了从我正在使用的表中获取聚合值的问题。我在下面提供样品。但从汇总的角度来看,我甚至不确定从哪里开始。我想我需要使用case和having的组合,但我不确定如何表达它。
我的表格如下:
Record# Value
111111 KA
111111 RA
111111 HA
111112 KA
111113 RA
111114 HA
111114 RA
期望的结果。我想得到的是获得记录的计数:
# Records only have KA only.
# Records only have RA only.
# Records only have RH only.
# Records only have HA only.
# Records only have KA and RA.
# Records only have KA and RH.
# Records only have KA, RA and RH.
and etc.
我的数量和价值有限,但我在那里有超过1,000,000条记录,我需要了解这些记录的构成。
我会为它创造一个小提琴,但它似乎目前已被打破。
create table myTable(record varchar2(100), value varchar2(100));
insert into myTable(record ,value) values(111111,'KA');
insert into myTable(record ,value) values(111111,'RA');
insert into myTable(record ,value) values(111111,'HA');
insert into myTable(record ,value) values(111112,'KA');
insert into myTable(record ,value) values(111113,'RA');
insert into myTable(record ,value) values(111114,'HA');
insert into myTable(record ,value) values(111114,'RA');
编辑*使用@ Gordon-Linoff建议的内容后,
select valuelist, count(*) as cnt
from (select record, listagg(value, ',') within group (order by value) as valuelist, count(*) as cnt
from mytable
group by record
) r
group by valuelist
order by cnt, valuelist;
我得到的混合结果看起来更像是
KA 2
RA 3
HA 2
而不是
KA, RA, HA 2
KA 1
RA 1
HA, RA 1
答案 0 :(得分:2)
您可以通过使用listagg()
组合字段然后按结果聚合来执行此操作:
select valuelist, count(*) as cnt
from (select record, listagg(value, ',') within group (order by value) as valuelist, count(*) as cnt
from mytable
group by record
) r
group by valuelist
order by cnt, valuelist;