SQL峰值每天

时间:2017-07-05 22:13:19

标签: mysql sql

我有一张桌子:

   id |  booking_time       | art   | weight
   ---+---------------------+-------+------
    1 | 2017-06-18 10:34:09 | wood  |  1000
    2 | 2017-06-18 11:31:11 | wood  |  2000
    3 | 2017-06-18 14:11:25 | stone |  1000
    4 | 2017-06-18 16:47:37 | wood  |  -300
    5 | 2017-06-19 10:49:21 | wood  |   100
    6 | 2017-06-19 12:41:02 | wood  | -1000
    7 | 2017-06-19 12:49:54 | wood  |   200

我想要得到的是每天的库存峰值:

   booking_day |  art  | peak
   ------------+-------+-------
    2017-06-18 | wood  | 3000
    2017-06-16 | stone | 1000
    2017-06-19 | wood  | 2800

因此,18.06库存量最高的木材将为3000(1000 + 2000);在一天结束时只剩下2700(1000 + 2000 - 300)

从19.06开始,我们从2700木材开始,从昨天达到峰值2800(2700 + 100);当天结束时留下的金额为2000(2700 + 100 - 1000 + 200)

甚至可以用SQL吗?也许我需要另一张桌来存储每日金额或类似的东西

1 个答案:

答案 0 :(得分:2)

您需要计算累积总和然后汇总:

select date(booking_time), art, max(running_stock)
from (select t.*,
             (@s := if(@a = t.art, @s + weight,
                       if @a := t.art, weight, weight)
                      )
             ) as running_stock
      from t cross join
           (select @s := 0, @a := 0) params
      order by t.art, t.booking_time
     ) t
group by date(booking_time), art;