我是 SQL Server 2014 的新手。我有一个包含如下记录的表。
Year | ItemName | price | effectivefromdate
===============================================
2018 | item27 | 1595.0000 | 2017-01-01
2018 | item27 | 1595.0000 | 2018-03-01
2018 | item29 | 1000.0000 | 2017-01-01
2018 | item29 | 1100.0000 | 2018-03-01
2018 | item30 | 1795.0000 | 2017-01-01
2018 | item30 | 1795.0000 | 2018-03-01
2018 | item30 | 1795.0000 | 2018-06-01
2018 | item32 | 1322.0000 | 2017-01-01
2018 | item32 | 1350.0000 | 2018-03-01
2018 | item32 | 1376.0000 | 2018-06-01
这里每件商品都有一行或多行,价格相同或不同。当价格发生其他变化时,我必须为每件商品取最近的生效日期 如果多个生效日期都没有价格变化,那么我必须退回具有最短生效日期的商品。
例如,item27 有两个条目,但价格没有改变,所以我必须将价格设为 1595,生效日期设为 2017-01-01 如果是item29,这里的价格已经改变了,我必须以1100为价格,生效日期为2018-03-01。
Expected Output
Year | ItemName | price | effectivefromdate
===============================================
2018 | item27 | 1595.0000 | 2017-01-01
2018 | item29 | 1100.0000 | 2018-03-01
2018 | item30 | 1795.0000 | 2017-01-01
2018 | item32 | 1376.0000 | 2018-06-01
我尝试使用滞后/超前功能,但没有成功。在过去的两天里,我一直在为此苦苦挣扎。
请给我一些解决方案来解决这个问题。
最佳答案
通过使用 Row_Number()
:
with cte as
(
Select Year, Itemname,price,effectivefromdate,
ROW_NUMBER() over (Partition by ItemName order by price desc, effectivefromdate asc) as ranking
from tbl
)
Select Year, Itemname,price,effectivefromdate from cte where ranking = 1
注意:这仅在价格随时间增加时有效。
关于sql - 在价格发生变化时查找每个项目的最新生效日期 - SQL Server 2014,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51061982/