我有一个SQL数据库与时间戳产品和价格。在此期间,一种产品的价格可能会发生多次变化。
我需要创建一个报表,它将只显示每个产品的价格变化,例如:
如果产品价格在周日是4美元,周一是4美元,周二是5美元,我想要显示:
Sunday $4
Tuesday $5
我希望跳过星期一,因为那天的价格没有变化,所以这并不重要。
感谢任何可以给我发送SQL查询的人。
发布于 2019-12-14 19:54:44
使用lag()
select t.*
from (select t.*,
lag(price) over (partition by product order by timestamp) as prev_price
from t
) t
where prev_price is null or prev_price <> price;
编辑:
旧版本的SQLite不支持窗口函数。一种方法是使用相关子查询:
select t.*
from (select t.*,
(select t2.price
from t t2
where t2.product = t.product and
t2.timestamp < t.timestamp
order by timestamp desc
limit 1
) as prev_price
from t
) t
where prev_price is null or prev_price <> price;
即使有了(product, timestamp, price)
上的索引,这也可能比以前的版本慢。
https://stackoverflow.com/questions/59338597
复制