我有50000名学生在不同的考试中心有不同的科目,在甲骨文表上这样:
Center_Code Roll_No PaperCode
10050 1 711
10050 2 711
10050 3 711
10050 4 711
10050 10 711
10050 11 711
10050 18 711
10050 21 711
10050 22 711
10050 23 711
10050 24 711
10050 25 711
10050 26 711
10050 27 711
10050 28 711
10050 29 711
10050 30 711
10050 31 711我希望每个中心最多有4名学生,并希望得到这样的输出:
Center_Code paprCode Roll_Nos students
10050 711 1-4 4
10050 711 10-11,18-18,21-21 4
10050 711 22-25 4
10050 711 26-29 4
10050 711 30-31 2发布于 2016-01-14 19:00:37
这是相对容易的,您只需要向原始数据集添加一些分析值就可以得到:
with grps as (
select t1.*
, trunc((row_number() over (partition by Center_Code, PaperCode order by Roll_No)-1)/4) grp_id
, roll_no - row_number() over (partition by Center_Code, PaperCode order by Roll_No) rng_id
from your_data t1
), rngs as (
select center_code
, papercode
, to_char(min(roll_no))||'-'||to_char(max(roll_no)) roll_nos
, min(roll_no) ord
, count(*) students
, grp_id
from grps
group by center_code, papercode, grp_id, rng_id
)
select center_code
, papercode
, LISTAGG(roll_nos, ', ') WITHIN GROUP (ORDER BY ord) roll_nos
, sum(students) students
from rngs
group by center_code, papercode, grp_id;在第一个子因素查询(grps)中,我计算一个分组id (grp_id),将roll_nos分为4组,范围id (rng_id),以便将每组4 roll_nos分组为连续范围。
在第二个子因素查询(rngs)中,对roll_nos的子范围进行合并和计数,并生成一个排序列(ord)。
在最后的输出查询中,使用listagg累积子范围,并计算最终的组大小。
https://dba.stackexchange.com/questions/126065
复制相似问题