我在确定如何对不同行进行求和时遇到麻烦,但是将每个分组的第一行用作起点。
我有一个看起来像这样的表:
+------+------+----------+---------------+----------+-------+
| Dim1 | Dim2 | Date | beg_Inventory | purchase | sales |
+------+------+----------+---------------+----------+-------+
| x | y | 1/1/2019 | 100 | 50 | 20 |
| x | y | 1/2/2019 | | 70 | 80 |
| x | y | 1/3/2019 | | 40 | 60 |
| x | y | 1/4/2019 | | 30 | 50 |
| x | y | 1/5/2019 | | 100 | 10 |
| x | z | 1/1/2019 | 65 | 10 | 50 |
| x | z | 1/2/2019 | | 20 | 5 |
| x | z | 1/3/2019 | | 40 | 5 |
+------+------+----------+---------------+----------+-------+
我想要一个看起来像这样的结果
+------+------+----------+---------------+----------+-------+------------+
| Dim1 | Dim2 | Date | beg_Inventory | purchase | sales | ending_inv |
+------+------+----------+---------------+----------+-------+------------+
| x | y | 1/1/2019 | 100 | 50 | 20 | 130 |
| x | y | 1/2/2019 | | 70 | 80 | 120 |
| x | y | 1/3/2019 | | 40 | 60 | 100 |
| x | y | 1/4/2019 | | 30 | 50 | 80 |
| x | y | 1/5/2019 | | 100 | 10 | 170 |
| x | z | 1/1/2019 | 65 | 10 | 50 | 25 |
| x | z | 1/2/2019 | | 20 | 5 | 40 |
| x | z | 1/3/2019 | | 40 | 5 | 75 |
+------+------+----------+---------------+----------+-------+------------+
期末库存为beg_inventory +购买-销售,每个dim1和dim2分组的第一行,即第一行为100 + 50-20 = 130 但是,在第二行中,它必须使用我们计算出的130,并在下一行中使用购买和销售来获得130 + 70-80 = 120,依此类推,按dim1和dim2分组并按日期排序。>
谢谢。
答案 0 :(得分:1)
尝试并使用first_value()
在窗口中获取beg_inventory
的第一个值,然后向其添加窗口化的sum()
的购买和销售。
SELECT dim1,
dim2,
date,
beg_inventory,
purchase,
sales,
first_value(beg_inventory) OVER (PARTITION BY dim1,
dim2
ORDER BY date)
+
sum(purchase - sales) OVER (PARTITION BY dim1,
dim2
ORDER BY date) ending_inv
FROM elbat
ORDER BY dim1,
dim2,
date;
答案 1 :(得分:0)
所有行的公式对我来说都是相同的
SELECT t.*,
SUM(COALESCE(beg_Inventory, 0) + purchase - sales) OVER (PARTITION BY dim1, dim2 ORDER BY date) as ending_inv
FROM t
ORDER BY dim1, dim2, date;