我正在尝试创建一个手动计算的列,以跟踪当前库存。
当前,我有一个看起来像这样的表:
| Group | Part | Operation Type | Transaction Amount |
|--------------|------|----------------|--------------------|
| Concrete | A | STOCK | 100 |
| Concrete | A | Buy | 25 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | A | Make | -10 |
| Concrete | B | STOCK | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | -10 |
| Concrete | B | Make | 150 |
| Construction | C | STOCK | 10 |
| Construction | C | Make | -1 |
| Construction | C | Make | -1 |
| Construction | C | Make | -1 |
| Construction | C | Make | -1 |
| Construction | D | STOCK | 5 |
| Construction | D | Make | -5 |
该表首先按group
排序,然后按part
排序,然后STOCK
始终显示为第一个值。这个想法是创建一个新的手动计算的列curr_inventory
,该列使我们可以跟踪当前库存,并查看给定零件,给定组的库存是否或何时下降到0以下。>
理想情况下,最终结果将如下所示:
| Group | Part | Operation Type | Transaction Amount | New_Inventory_Column |
|:------------:|:----:|:--------------:|:------------------:|:--------------------:|
| Concrete | A | STOCK | 100 | 100 |
| Concrete | A | Buy | 25 | 125 |
| Concrete | A | Make | -10 | 115 |
| Concrete | A | Make | -10 | 105 |
| Concrete | A | Make | -10 | 95 |
| Concrete | A | Make | -10 | 85 |
| Concrete | A | Make | -10 | 75 |
| Concrete | B | STOCK | 10 | 10 |
| Concrete | B | Make | -10 | 0 |
| Concrete | B | Make | -10 | -10 |
| Concrete | B | Make | -10 | -20 |
| Concrete | B | Make | -10 | -30 |
| Concrete | B | Make | 150 | 120 |
| Construction | C | STOCK | 10 | 10 |
| Construction | C | Make | -1 | 9 |
| Construction | C | Make | -1 | 8 |
| Construction | C | Make | -1 | 7 |
| Construction | C | Make | -1 | 6 |
| Construction | D | STOCK | 5 | 5 |
| Construction | D | Make | -5 | 0 |
最终结果将是一列,该列在零件号更改且操作类型为STOCK时启动,然后开始(使用交易金额)计算当前库存量。 我不确定从哪里开始执行SQL查询。直观地,伪代码看起来像:
for each row in table:
if operation_type == "stock":
curr_inv = stock.value
else:
curr_inv = previous_curr_inv + transaction_amount
但是,我不确定如何开始为此编写SQL。我通常尝试发布正在使用的SQL,但我什至不知道从哪里开始。我在网上在线浏览了各种帖子,包括帖子like this,and this,and this,但是我看不到如何将所选答案用作解决方案。
答案 0 :(得分:1)
我使用了窗口函数来计算运行总计。
我在子查询中添加了row_number列。
尝试一下:
select t1."Group",t1."Part",t1."Operation Type", t1."Transaction Amount",
sum(t1."Transaction Amount") over (partition by t1."Group",t1."Part" order by t1.rownumber)
from (
select row_number() over (order by null) as rownumber, t.*
from test t ) t1
测试结果:
答案 1 :(得分:0)
SQL表表示无序集。为了使事情井井有条,您需要一列排序。在下面的代码中,我将在此列中使用?
。
然后,您需要累计金额:
select t.*,
sum(case when operation_type in ('STOCK'),
when operation_type in ('Make') then - amount
when operation_type in ('Buy') then - amount
else 0
end) over (partition by group, part order by ?)
from t;