Reputation: 585
I have the following dataset:
DATA_FIM CENTRO C M ESTOQUE
2018-02-01 HD01 CD 70 539.000
2018-03-01 HD01 CD 70 511.000
2018-04-01 HD01 CD 70 468.000
2018-05-01 HD01 CD 70 447.000
2018-06-01 HD01 CD 70 382.000
2018-07-01 HD01 CD 70 348.000
2018-08-01 HD01 CD 70 285.000
2018-09-01 HD01 CD 70 245.000
2018-10-01 HD01 CD 70 221.000
2018-11-01 HD01 CD 70 207.000
2018-12-01 HD01 CD 70 122.000
2018-12-21 HD01 CD 70 101.000
2018-02-01 HD01 CD 71 164.000
2018-03-01 HD01 CD 71 147.000
2018-04-01 HD01 CD 71 124.000
2018-05-01 HD01 CD 71 107.000
2018-06-01 HD01 CD 71 78.000
1- Considering the 2nd, 3rd, 4th columns as a group, I want to subtract the 5th column values from previous row of same column.
In order to create a new row.
[![Data][2]][2]
It's very similar with this problem: [Issue:13196190][3], however, in my case I have multiple index, and I am not sure how to solve.
I am using the suggested codes
select
ZBI_FAT_PRODUCT.DATA_FIM,
ZBI_DIM_EMPRESA.CENTRO,
ZBI_DIM_EMPRESA.CANAL,
ZBI_DIM_PRODUCT.MATERIAL,
ZBI_DIM_PRODUCT.TITULO,
ZBI_FAT_PRODUCT.ESTOQUE_VENDA,
LAG(ZBI_FAT_PRODUCT.ESTOQUE_VENDA, 1, ZBI_FAT_PRODUCT.ESTOQUE_VENDA) OVER (PARTITION BY ZBI_DIM_EMPRESA.CENTRO, ZBI_DIM_PRODUCT.MATERIAL, ZBI_DIM_PRODUCT.TITULO ORDER BY ZBI_FAT_PRODUCT.DATA_FIM) - ZBI_FAT_PRODUCT.ESTOQUE_VENDA AS NEW
FROM ZBI_DIM_EMPRESA INNER JOIN (ZBI_DIM_PRODUCT INNER JOIN ZBI_FAT_PRODUCT ON ZBI_DIM_PRODUCT.BK = ZBI_FAT_PRODUCT.BK_MATERIAL) ON ZBI_DIM_EMPRESA.BK = ZBI_FAT_PRODUCT.BK_EMPRESA;
Upvotes: 0
Views: 1316
Reputation: 1801
For brevity, and to extract the solution from the comments -
The answer is to use the LAG()
function:
SELECT *,
LAG(ESTOQUE, 1, ESTOQUE) OVER (PARTITION BY CENTRO, C, M ORDER BY DATA_FIM) - ESTOQUE AS New
FROM EnergyLog
Here is an example of this working: SQLFiddle
Upvotes: 1
Reputation: 1271241
You seem to just want lag()
:
select el.*,
(lag(estoque, 0, estoque) over (partition by centro, c, m order by date_mif) -
estoque
) as diff
from energylog el;
EDIT:
For the edited question, only two columns seem to comprise a group
select el.*,
(lag(estoque, 0, value) over (partition by centro, canal, order by date_mif) -
estoque
) as diff
from energylog el;
Upvotes: 5