从库存表中找出库存为零的两个日期之间的日期

时间:2019-05-21 03:54:48

标签: sql-server

我有一个SQL表https://pasteboard.co/IfFt5rF.png,其中包含成千上万个有关产品流的记录,如果出售了产品,数量为负,而购买时为正。 product_id是每个产品的唯一标识符。我想输入日期,并找出该日期(库存为零)之间的每个月。

我当时想首先计算每个月的期初余额,方法是找出过去期间的总和,然后逐行添加新数据,如果该数据为零,则添加一个日期,但是这种逻辑看起来非常糟糕,甚至不知道如何在SQL中处理该问题。

我使用Microsoft SQL 2014

declare @Table table (general_id bigint, date datetime, product_id bigint, quantity float, 
price float, code nvarchar(max), name nvarchar(max), partnumber nvarchar(max), 
description nvarchar(max), rate float, comment nvarchar(max), currency nvarchar(max), waybill nvarchar(max))

insert into @Table (general_id, date, product_id, quantity, price, code, name, partnumber, description, rate, comment, currency, waybill)
  select 1, '2019-03-1 16:33:00', 1, 10, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
  union all
  select 2, '2019-03-2 16:33:09', 1, -5, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
  union all
  select 3, '2019-03-3 16:33:12', 1, -3, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
  union all
  select 4, '2019-03-4 16:39:00', 1, -2, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
  union all
  select 5, '2019-03-4 16:39:41', 2, 40, 100, 102020, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
  union all
  select 6, '2019-03-5 16:39:00', 2, -40, 100, 202020, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
  union all
  select 7, '2019-03-6 16:39:00', 1, 25, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'


SELECT DISTINCT product_id, code, name, partnumber, SUM(quantity) 
FROM @TABLE
GROUP BY product_id, code, name, partnumber 
ORDER BY product_id ASC                                 

如果输入的日期范围为2019-03-01至2019-03-31,则当前情况的输出为。 product_id:1 缺货日期:2019-03-4 zero_stock_days:2,因为在2019-03-6时该商品已购买并且已经库存

product_id:2 缺货日期:2019-03-5 zero_stock_days:26,因为再也没有购买

1 个答案:

答案 0 :(得分:1)

使用Sql Server> 2008中可用的窗口函数尝试此查询:)

protected function errorResponse($message, $code)
    {
        return response()->json(['error' => $message, 'code' => $code], $code);
    }