我有一张满是价格,物品和日期的桌子。这样的一个例子是:
AA, 1/2/3024, 1.22 AA, 1/3/3024, 1.23 BB, 1/2/3024, 4.22 BB, 1/3/3024, 4.23
在数据中,每个价格只有两行,并且按日期排序。我如何将该数据集压缩到一个产品行中,以显示从最后价格到前一个价格的差异?[这也适用于比率,因此AA将产生1.23/ 1.22]。
结果应该看起来像
AA, todays price-yesterdays price
尽管是求和函数,但列表上没有减法函数。
我正在使用postgres 9.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