我有下表格式的表格(按地点和月份/日期划分的产品成本),并希望在费用发生变化时获得最小的ChangeDate。
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(PartitionBy OrderBy),但问题是 由于成本1.223000000000重复两次,我无法正确分区,因此只能获得3条记录。
答案 0 :(得分: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