Oracle SQL - 将连续数字设置为范围

时间:2013-10-09 10:51:41

标签: sql oracle

此查询返回以下结果...

WITH t(wk, COST) AS
(SELECT wk, COST FROM myTable WHERE id = '345')
SELECT listagg(wk,',') WITHIN GROUP(ORDER BY wk) AS wks, COST 
FROM   t
GROUP BY COST;

...

WKS               COST
----------------------
17, 18, 19, 21    446
26, 27, 28        588

是否可以创建以下结果,其中连续几周返回为from和to。 (例如1-10而不是1,2,3,4 ......等)

WKS               COST
----------------------
17-19, 21         446
26-28             588

1 个答案:

答案 0 :(得分:3)

在这个问题中,您必须确定连续周的序列并对它们进行分组。这是我的解决方案。

  • 使用LAG功能识别序列中的任何中断。
  • 使用SUM功能为每个序列分配组编号。
  • 查找每个小组的开始和结束周。
  • 最后使用LISTAGG函数聚合结果。

查询:

with x(wk, cost, startgroup) as(
    --identify the start of a sequence
    select wk, cost,
           case when wk = lag(wk,1) over (partition by cost order by wk) + 1
                then 0
                else 1
             end
    from mytable
    where id = '345'
    ),
    y(wk, cost, grp) as(
    --assign group number
    select wk, cost,
           sum(startgroup) over (partition by cost order by wk)
    from x
    ),
    z(wk, cost, grp) as(
    --get the max/min week for each group
    select case when min(wk) = max(wk)
                then cast(min(wk) as varchar2(10))
                else min(wk) ||'-'||max(wk)
                end,
            cost, grp
    from y
    group by cost, grp
    )
--aggregate by cost
select listagg(wk,',') within group(order by grp),
cost
from z
group by cost;

sqlfiddle的演示。