SQL - 筛选数据仅显示更改历史记录
SQL - Filter Data only showing changes history
我有一个 table 看起来像:
| ID_Product | Product | Price | Date |
------------------------------------------------------
| 01 | Socks | | 2020-06-02 18:27:49.000 |
| 03 | Belt | | 2020-06-03 13:27:08.000 |
| 01 | Socks | | 2020-06-11 17:00:04.000 |
| 02 | Boots | | 2020-06-12 09:27:19.000 |
| 02 | Boots | | 2020-06-17 11:27:10.000 |
| 01 | Socks | | 2020-06-25 15:29:45.000 |
| 01 | Socks | | 2020-07-08 16:27:30.000 |
我需要一个查询来按价格和日期获取不同的行,以获取一些价格变化的“历史记录”,就像这样
| ID_Product | Product | Price | Date |
------------------------------------------------------
| 03 | Belt | | 2020-06-03 13:27:08.000 |
| 01 | Socks | | 2020-06-11 17:00:04.000 |
| 02 | Boots | | 2020-06-17 11:27:10.000 |
| 01 | Socks | | 2020-06-25 15:29:45.000 |
| 01 | Socks | | 2020-07-08 16:27:30.000 |
谢谢!
您似乎只想要每个产品价格的最新日期:
select product_id, price, max(date)
from t
group by product_id, price;
我以为您想知道新价格何时开始生效。为了那个原因,
您可以使用 lag()
查看价格何时变化 - 并仅保留这些行:
select t.*
from (select t.*,
lag(price) over (partition by product_id order by date) as prev_price
from t
) t
where prev_price is null or prev_price <> price;
我有一个 table 看起来像:
| ID_Product | Product | Price | Date | ------------------------------------------------------ | 01 | Socks | | 2020-06-02 18:27:49.000 | | 03 | Belt | | 2020-06-03 13:27:08.000 | | 01 | Socks | | 2020-06-11 17:00:04.000 | | 02 | Boots | | 2020-06-12 09:27:19.000 | | 02 | Boots | | 2020-06-17 11:27:10.000 | | 01 | Socks | | 2020-06-25 15:29:45.000 | | 01 | Socks | | 2020-07-08 16:27:30.000 |
我需要一个查询来按价格和日期获取不同的行,以获取一些价格变化的“历史记录”,就像这样
| ID_Product | Product | Price | Date | ------------------------------------------------------ | 03 | Belt | | 2020-06-03 13:27:08.000 | | 01 | Socks | | 2020-06-11 17:00:04.000 | | 02 | Boots | | 2020-06-17 11:27:10.000 | | 01 | Socks | | 2020-06-25 15:29:45.000 | | 01 | Socks | | 2020-07-08 16:27:30.000 |
谢谢!
您似乎只想要每个产品价格的最新日期:
select product_id, price, max(date)
from t
group by product_id, price;
我以为您想知道新价格何时开始生效。为了那个原因,
您可以使用 lag()
查看价格何时变化 - 并仅保留这些行:
select t.*
from (select t.*,
lag(price) over (partition by product_id order by date) as prev_price
from t
) t
where prev_price is null or prev_price <> price;