如何构造SQL查询以查找随时间变化的值

时间:2018-10-21 07:36:19

标签: sql

我有一张桌子

product_id | price | date
1            1       2018-10-01
2            1       2018-10-01
3            1       2018-10-01
4            1       2018-10-01
1            1       2018-11-01
2            1       2018-11-01
3            3       2018-11-01
4            2       2018-11-01

我在编写查询时遇到了麻烦,该查询只会给我提供 价格已更改,按产品和日期排序

product_id | price | date
3            1       2018-10-01
3            3       2018-11-01
4            1       2018-10-01
4            2       2018-11-01

谢谢!

3 个答案:

答案 0 :(得分:2)

您只需要查找数据库中该产品行有不同价格的产品:

SELECT p.product_id, p.price, p.date
FROM products p
JOIN products p1
ON p1.product_id = p.product_id AND p1.price != p.price
ORDER BY p.product_id, p.date

输出:

product_id  price   date
3           1       2018-10-01
3           3       2018-11-01
4           1       2018-10-01
4           2       2018-11-01

Demo on dbfiddle

答案 1 :(得分:0)

我将为此目的使用窗口函数:

SELECT p.product_id, p.price, p.date
FROM (SELECT p.*,
             LAG(p.price) OVER (PARTITION BY p.product_id ORDER BY p.date) as prev_price,
             LEAD(p.price) OVER (PARTITION BY p.product_id ORDER BY p.date) as next_price
      FROM products p
     ) p
WHERE prev_price <> price OR next_price <> price
ORDER BY p.product_id, p.date;

我通常希望此信息在每次价格变动的一行中显示。该查询是:

SELECT p.product_id, p.price, p.date, p.prev_price, p.prev_date
FROM (SELECT p.*,
             LAG(p.price) OVER (PARTITION BY p.product_id ORDER BY p.date) as prev_price,
             LAG(p.date) OVER (PARTITION BY p.product_id ORDER BY p.date) as prev_date
      FROM products p
     ) p
WHERE prev_price <> price
ORDER BY p.product_id, p.date

答案 2 :(得分:0)

您应该能够仅按product_id和价格进行分组

select product_id, price, min(date) as date
group by product_id,price
having count(date) > 1
order by 1,2