3

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

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
4

1 回答 1

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演示。

于 2013-10-09T11:32:24.573 回答