不同唯一ID的连续行之间的差异

时间:2019-01-14 13:14:46

标签: mysql

enter image description here我正在研究一个问题,我想让sql中不同ID的连续行的Avg_price之间的差异

我希望在sql中为新ID启动时为Null或零值。

我希望o / p列的id为零,以2和3开头,并且类似。

我尝试了分区方式,但是没有成功。

SET @tmp := -1;

SELECT @n := @n + 1 n,W.*,if(@tmp =-1, 0, W.Avg_price - @tmp) as 'o/p',@tmp:=W.Avg_price as dummy   
  from (  
  Select A.id,A.year, A.Avg_price       
    from     
    (Select products.id,substring(orders.placed_on,1,4) as year, Avg(order_items.price ) as Avg_price 
     from 
     order_items 
     Inner Join orders
     ON order_items.order = orders.id 
     Inner Join product_variations 
     ON product_variations.id = order_items.product_variation 
     Inner Join products 
     ON products.id = product_variations.product 
     Group By products.id,substring(orders.placed_on,1,4)
    ) as A 
  ) as W,(SELECT @n := 0) m ;

预期输出: enter image description here

0 个答案:

没有答案