SQL-按日期计算库存移动

时间:2018-12-28 17:18:18

标签: sql sql-server

使用SQL Server 2008,我有一个包含列Date, ItemID, OpeningStockBalance的表。

例如,下面三个ItemID的三天数据。

26/12/2018, 000001, 10
26/12/2018, 000002, 5
26/12/2018, 000003, 15
27/12/2018, 000001, 8
27/12/2018, 000002, 4
27/12/2018, 000003, 14
28/12/2018, 000001, 6
28/12/2018, 000002, 3
28/12/2018, 000003, 10

我想通过从最近的日期开始并向后计算得出ItemID的按天计算的销售额,即对于ItemID 000001,在28日,库存余额为6,但在8月因此排在第27位,销量为2。

所需的输出(Date, ItemID, Sales

27/12/2018, 000001, 2
27/12/2018, 000002, 1
27/12/2018, 000003, 4
26/12/2018, 000001, 2
26/12/2018, 000002, 1
26/12/2018, 000003, 1

预先为可怕的格式表示歉意,但不确定如何换行!

3 个答案:

答案 0 :(得分:0)

您似乎想要lead()

select date, itemId,
       (OpeningStockBalance - next_OpeningStockBalance) as sales
from (select t.*,
             lead(OpeningStockBalance) over (partition by itemID order by date) as next_OpeningStockBalance
      from t
     ) t
where next_OpeningStockBalance is null

答案 1 :(得分:0)

通过从相邻日期中减去2个值来创建销售列:

select 
  t.date, 
  t.itemid, 
  (select 
    openingstockbalance 
    from stock as s 
    where 
      s.itemid = t.itemid
      and 
      s.date = DATEADD(day, -1, t.date)) - t.openingstockbalance as sales
from stock as t 
where t.date <> (select min(date) from stock)
order by t.date desc, t.itemid

答案 2 :(得分:0)

要在2008年模仿超前/滞后,可以在原始表中添加序列号,并在自连接中使用它(请参见下面的代码)。但是,如果您只需要前一个日历日的销售,则可以按照其他帖子的建议使用subselect。

,M as (
select T.*, ROW_NUMBER() over (partition by itemID order by date) rn from T
)

select M1.*, (m1.sales - m2.sales) as prev_day_sales
from M M1
 inner join M M2 on m2.ItemID = m1.ItemID and m1.rn = m2.rn - 1
order by 2, 1 desc