sql - 在价格发生变化时查找每个项目的最新生效日期 - SQL Server 2014

标签 sql sql-server sql-server-2012 sql-server-2008-r2 sql-server-2014

我是 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/

相关文章:

php - PDO BindValue 不起作用 - 执行不返回任何内容

sql - 通过连接不同服务器上两个数据库中的两个表来查询数据

sql - 如何提高 SQL Server 中日期时间过滤的性能?

performance - 为什么交叉应用比内连接快?

sql - T-SQL-连接变量行数

sql - 将事务存储到 NoSQL 数据库中

mysql - 如何从两个表中编写选择查询

mysql - 如何使用 24 小时制从 SQL Server 获取以分钟为单位的时差?

sql-server - SQL Server ,限制 UNPIVOT 自动对列进行排序

sql - 优化数百万行的自连接