如何使用SQL查询获得正确的库存演变?

时间:2019-03-29 13:34:37

标签: mysql

我有示例数据和逻辑;我需要更正我的SQL查询。

预期结果:

ShippedData | DayEnd | DayStart  | Quantity | Daysales  | Reorderunits
------------+--------+-----------+----------+-----------+-------------
 1998-05-01 |   39   |     64    |    25    |    39     |      0
 1998-04-24 |   64   |     75    |    65    |    10     |     54

我的输出:

ShippedData | DayEnd | DayStart  | Quantity | Daysales  | Reorderunits
------------+--------+-----------+----------+-----------+-------------
 1998-05-01 |   39   |     64    |    25    |    39     |      0
 1998-04-24 |   64   |    104    |    65    |    10     |    (null)

逻辑

  • 第一行有DayEnd = UnitsinStock
  • 第二行的DayEnd等于DayStart的先前值
  • ReorderUnits = DayEnd - DaySales
  • DayStart = (Quantity + Daysales)

我在第二行的DayStart中得到了错误的值:应该是65 + 10 = 75 而且不知道如何在第二个联合中计算ReorderUnits

代码

select  max(ShippedDate)ShippedDate,
        UnitsInStock as DayEnd ,
        Quantity + case when (UnitsInStock <= reorderlevel*4) then UnitsInStock
                        else reorderlevel end DayStart,
        Quantity, 
        case when (UnitsInStock <= reorderlevel*4) 
                then UnitsInStock
                else reorderlevel end DaySales,  
        UnitsOnOrder as Reorderunits 
from    dummy
where   ShippedDate = (select max(ShippedDate) from dummy) 
group by ShippedDate
union
select  ShippedDate, 
        round(previous_operation) as DayEnd, 
        DayStart,
        Quantity,
        DaySales,
        null as Reorderunits 
from    (   select  y.*, 
                    @prev AS previous_Operation,
                    @prev := Quantity + case when (UnitsInStock <= reorderlevel*4) 
                                                then UnitsInStock
                                                else reorderlevel end DayStart,
                    @prev :=  DayStart,
                    case when (@prev <= reorderlevel*4) 
                            then UnitsInStock
                            else reorderlevel end DaySales
                from    dummy  y,
                        (select @prev:=null) vars
                order by ShippedDate desc
        ) subquery_alias
where   previous_operation is not null
order by ShippedDate desc

1 个答案:

答案 0 :(得分:0)

当您需要按顺序比较同一张表中的记录时,您应该跳到rank functionrow_number function。请注意,<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="empleadores"> <div class="lista-empleadores lista-empleadores-1"> <div class="vista-empleador"> A </div> </div> <button class="clone-lista">Clone</button> <div class="lista-empleadores lista-empleadores-2"> <div class="vista-empleador"> B </div> </div> <button class="clone-lista">Clone</button> </div>仅在MySQL 8.0+中可用。请注意,当row_number子句中rank列的值重复时,order by会很有趣。

我们可以通过基于行号将表与其自身连接来完成此操作。通过从一个表实例的行号中减去1,我们可以得到一条记录,其中两天彼此依序偏移1。

这是不完整的答案,因为我无法理解您对over的定义。我认为,我已经准确地捕获了其余的定义,但是如果没有示例数据和表定义,我将无法进行测试。

DaySales