我有物品价格的db日志。有时(通常是每个月)新的状态将价格存储到db中。 每个项目都有uniqueid。它每个月都不会发生变化。
我已经构建了示例数据库:
http://sqlfiddle.com/#!6/0bc28/3
我需要检测商品价格变化。例如 如果2013-01-01的item1价格为122,则2013-02-01为122,2013-03-01为124
选择应显示1行 itemname = item1,oldPrice = 122,newPrice = 124,dateCHanged = 2013-03-01
答案 0 :(得分:2)
这应该有效:
with x as (
select i.*, s.datecreated, row_number() over (partition by uniqueid order by datecreated) as rn
from items i
inner join states s on i.stateid = s.id
)
select x1.uniqueId, x1.price as oldPrice, x2.price as newPrice, x2.dateCreated as dateChanged
from x x1
inner join x x2 on x1.uniqueid = x2.uniqueid
--and datediff(month, x1.datecreated, x2.datecreated) = 1
and x1.rn - x2.rn = 1
and x1.price <> x2.price