按组减去上一行sql的值

时间:2019-05-29 12:55:18

标签: sql sql-server

我有以下数据集:

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-以第二,第三,第四列为一组,我想从同一列的上一行中减去第五列的值。

为了创建新行。

[![数据] [2]] [2]

这个问题非常相似:[问题:13196190] [3],但是,在我的情况下,我有多个索引,并且不确定如何解决。

已更新

我正在使用建议的密码

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;

2 个答案:

答案 0 :(得分:4)

您似乎只想要lag()

select el.*,
       (lag(estoque, 0, estoque) over (partition by centro, c, m order by date_mif) -
        estoque
       ) as diff
from energylog el;

编辑:

对于已编辑的问题,似乎只有两列组成一个组

select el.*,
       (lag(estoque, 0, value) over (partition by centro, canal, order by date_mif) -
        estoque
       ) as diff
from energylog el;

答案 1 :(得分:1)

为简洁起见,并从评论中提取解决方案-

答案是使用LAG()函数:

SELECT *, 
LAG(ESTOQUE, 1, ESTOQUE) OVER (PARTITION BY CENTRO, C, M ORDER BY DATA_FIM) - ESTOQUE AS New
FROM EnergyLog

以下是此工作的示例:SQLFiddle