我正在尝试从数据库中提取统计信息。 表的结构是:
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=(选择 min(revenue)来自 updated_stats 其中 product_name=a.product_name and revenue > a.revenue and product_name= 'Product1')
请问应该怎么查询?谢谢。
最佳答案
我会用相关的子查询来做到这一点:
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;
注意:对于 970,这将返回 NULL
而不是 0。这实际上对我来说更有意义。但是您可以使用 COALESCE()
或类似的函数将其变成 0。
如果 updated_stats
的大小适中,您将需要一个关于 updated_status(product_name, updated_id, revenue)
的索引。该索引涵盖了子查询。
关于MySql Select - 行减去上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44750107/