我有一个表格(按地点和月份/日期划分的产品成本),格式如下,我想获得成本发生变化时的最小变化日期。
Cost Loc Prod ChangeDate
--------------------------------------------------------
1.223000000000 5678 12345678 2010-01-03 00:00:00
1.223000000000 5678 12345678 2010-01-31 00:00:00
1.223000000000 5678 12345678 2010-02-28 00:00:00
1.000000000000 5678 12345678 2010-04-04 00:00:00
1.223000000000 5678 12345678 2010-05-02 00:00:00
1.223000000000 5678 12345678 2010-05-30 00:00:00
1.223000000000 5678 12345678 2010-07-04 00:00:00
1.277200000000 5678 12345678 2010-08-01 00:00:00
1.277200000000 5678 12345678 2010-08-29 00:00:00
1.277200000000 5678 12345678 2010-10-03 00:00:00
期望输出:
Cost Loc Prod CostChangeStartDate
------------------------------------------------
1.223000000000 5678 12345678 2010-01-03 00:00:00
1.000000000000 5678 12345678 2010-04-04 00:00:00
1.223000000000 5678 12345678 2010-05-02 00:00:00
1.277200000000 5678 12345678 2010-08-01 00:00:00
我尝试使用Row_Number() Over(partitionbyorderby),但问题是因为Cost 1.223000000000重复了两次,所以我无法正确分区它,所以只得到3条记录。
您可以使用LAG
:
select * from (
select *, lag(cost, 1) over (partition by Loc, Prod order by ChangeDate) prevCost
from @products
) x
where prevCost is null or cost <> prevCost