我有一张满是价格、物品和日期的桌子。例如:

AA, 1/2/3024, 1.22
AA, 1/3/3024, 1.23
BB, 1/2/3024, 4.22
BB, 1/3/3024, 4.23

在数据中,每个价格只有两行,它们是按日期排序的。如何将此数据集压缩为显示上一个价格与上一个价格之间差异的单个产品行?[这也适用于比率,因此a a将产生1.23/1.22]。
结果应该是
AA, todays price-yesterdays price

尽管是求和函数,但列表上没有减法函数。
我在用Postgres9.1。

最佳答案

select product,
       sales_date,
       current_price - prev_price as diff
from (
  select product,
         sales_date,
         price as current_price,
         lag(price) over (partition by product order by sales_date) as prev_price,
         row_number() over (partition by product order by sales_date desc) as rn
  from the_unknown_table
) t
where rn = 1;

SQLFiddle示例:http://sqlfiddle.com/#!15/9f7d6/1

10-04 10:53
查看更多