3

我正在尝试从数据库中提取统计信息。表的结构是:

UpdatedId product_name   revenue
980       Product1       1000
975       Product1       950
973       Product1       900
970       Product1       800
965       Product21      1200

所以收入=以前的收入+新的收入。

为了制作图表,目标是像这样获得 Product1 的输出

UpdateId  Difference
980       50 
975       50 
973       100 
970       0 

我试过这个查询,但 MySQL 卡住了 :)

选择 a.product_name、a.revenue、b.revenue、b.revenue- a.revenue 作为与 updated_stats a、updated_stats b 的差异,其中 a.product_name=b.product_name 和 b.revenue= (select min(revenue) from updated_stats where product_name=a.product_name 和收入 > a.revenue 和 product_name='Product1')

你能告诉我,它应该如何查询?谢谢。

4

1 回答 1

2

我会用一个相关的子查询来做到这一点:

select u.*,
       (select u.revenue - u2.revenue
        from updated_stats u2
        where u2.product_name = u.product_name and
              u2.updatedid < u.updatedid
        order by u2.updatedid desc
        limit 1
       ) as diff
from updated_stats u;

注意:这将返回NULL970 而不是 0。这对我来说实际上更有意义。但是您可以使用COALESCE()或类似的功能将其变为 0。

如果updated_stats大小适中,您将需要在updated_status(product_name, updated_id, revenue). 该索引涵盖子查询。

于 2017-06-25T20:05:16.230 回答