此查询返回以下结果...
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
答案 0 :(得分:3)
在这个问题中,您必须确定连续周的序列并对它们进行分组。这是我的解决方案。
查询:
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的演示。