我构建了我的查询,以便到目前为止,它显示以下数据:
ORDERNUM PARTNO ORDERQTY USEQTY
1112 0144 1 2
1113 0144 1 2
1114 0144 1 2
1115 0144 1 2
我现在需要做的是弄清楚如何操作USEQTY列,或者创建一个新的列,它从初始值中依次减去。 PARTNO中所有这些订单项之间存在共同链接。 USEQTY列不能大于ORDERQTY列,对于每个顺序ORDERNUM,应从USE QTY中减去ORDERQTY。下面是表格的外观:
ORDERNUM PARTNO ORDERQTY USEQTY
1112 0144 1 1
1113 0144 1 1
1114 0144 1 0
1115 0144 1 0
我应该在这里做分区吗?
答案 0 :(得分:2)
with
test_data ( ordernum, partno, orderqty, useqty ) as (
select 1112, 0144, 1, 2 from dual union all
select 1113, 0144, 1, 2 from dual union all
select 1114, 0144, 1, 2 from dual union all
select 1115, 0144, 1, 2 from dual
)
-- end of test data; solution (SQL query) begins below this line
select ordernum, partno, orderqty,
greatest(useqty - coalesce(sum(orderqty)
over (partition by partno order by ordernum
rows between unbounded preceding and 1 preceding)
, 0)
, 0) as useqty
from test_data
order by partno, ordernum -- if needed
;
ORDERNUM PARTNO ORDERQTY USEQTY
---------- ---------- ---------- ----------
1112 144 1 2
1113 144 1 1
1114 144 1 0
1115 144 1 0
4 rows selected.
话虽如此,如果你回到一两步,这可能会更有效地完成(不要使用你在原帖中显示的作为中间步骤)。尤其是USEQTY专栏不应该是"输入"这个查询;无论其来源如何,都应直接使用初始数量或数量。