计算供应和销售中的库存天数

时间:2018-07-30 09:03:16

标签: sql sql-server sql-server-2014

我有两个汇总表。 Supplies包含收到的产品数量,Sales包含总销售额。我需要找出该产品有多少天(没有库存)。例如。从10.10.20171.5.2018的期间内,666的库存193 (11)在总的204天中没有库存。我想显示一些查询,但是我真的不知道从哪里开始。预期结果应该是这样的。

+----------------------------------------------------------------+
|        Period         | ProductID | Days in stock | Days total |
+----------------------------------------------------------------+
| 2017-10-10 - 2018-5-1 |       666 |           193 |        204 |
+----------------------------------------------------------------+

耗材

+--------------+-----------+----------+
| DeliveryDate | ProductID | Quantity |
+--------------+-----------+----------+
| 2018-07-27   |       666 |       20 |
| 2018-05-04   |       666 |       10 |
| 2018-04-20   |       666 |        1 |
| 2017-07-29   |       666 |       10 |
+--------------+-----------+----------+

销售

+-------------+-----------+----------+
| SummaryDate | ProductID | Quantity |
+-------------+-----------+----------+
| 2018-07-21  |       666 |        4 |
| 2018-07-14  |       666 |        4 |
| 2018-04-20  |       666 |       11 |
+-------------+-----------+----------+

SQL Fiddle

2 个答案:

答案 0 :(得分:2)

您需要执行一些步骤:在一栏中获取和获取值。如果在同一天,请将它们加起来。然后建立一个运行总计。然后检测库存何时以及多长时间为零。最后得到没有库存的总天数:

with in_and_out as
(
  select date, productid, sum(quantity) as quantity
  from
  (
    select deliverydate as date, productid, quantity from supplies
    union all
    select summarydate as date, productid, -quantity as quantity from sales
  ) in_and_out_raw
  group by date, productid
)
, running_totals as
(
  select date, productid, quantity, sum(quantity) over (partition by productid order by date) as total
  from in_and_out
)
, gaps_detected as
(
  select
    productid,
    case when total <= 0 then datediff(day, date, lead(date) over (partition by (productid) order by date)) end as diff
  from running_totals
)
select productid, sum(diff)
from gaps_detected
group by productid
order by productid;

SQL小提琴:http://www.sqlfiddle.com/#!18/3151d/21

答案 1 :(得分:0)

将它们放在一起,使用一些滞后量以获得运行中的总库存量

with CTE as
(
select DeliveryDate as TheDate,
       ProductID,
       Quantity
from Supplies
union all
select SummaryDate,
       ProductID,
       Quantity * (-1)
from sales
)

select t1.*, 
       Quantity + lag (Quantity) over (partition by ProductID order by TheDate) as Stock
from CTE t1

您应该能够操纵它以显示所需的信息。