sql查询获取要插入的一列的前一行值作为另一列的第二行值

时间:2016-12-24 18:00:48

标签: php sql

我的表结构是这样的

username   Period  Numberproduced  stockonhand   totalavailableforsale  actualsale  Inventoryremaining

pranab      1       100               2000           2100                 2000        100
pranab      2       200               100             300                  500         0
pranab      3       400               0               400                  100        300 
pranab      4       500               300             800                  400        400

期间-1的库存总是恒定= 2000。

期间-2的库存是=期间-1的库存剩余和&等等

请告诉查询执行此操作。

2 个答案:

答案 0 :(得分:0)

如果Period字段是唯一且递增的,那么此解决方案应该有效:

SELECT
    A.*
    , [stockinhand] = IIF(A.[Period] = 1, 2000, B.[inventoryremaining])
FROM
    [Table] AS A
        CROSS APPLY
    (SELECT TOP 1 *
    FROM
        [Table] AS B
    WHERE
        A.[Period] > B.[Period]
    ORDER BY
        B.[Period] DESC
    ) AS B

另请注意,如果您使用的是SQL Server 2012或更高版本,LAGLEAD子句将简化解决方案。

答案 1 :(得分:0)

如果period是连续的(无间隙),请使用 -

select  t.*
       ,coalesce
        (
           (select      Inventoryremaining 
            from        mytable as t2 
            where       t2.period = t.period - 1
            )
           ,2000
        )  as stockonhand   

from    mytable t

否则使用 -

select  t.*
       ,coalesce
        (
           (select      Inventoryremaining 
            from        mytable as t2 
            where       t2.period < t.period 
            order by    t2.period 
            desc        limit 1
            )
           ,2000
        )  as stockonhand   

from    mytable t