我试图从源表中插入数据到目标表中,在目标表中我有一个名为SaleTo的附加列.
SaleTo=基于MAX SaleSequence的salesfrom。
源表示例:
SaleNo | SaleFrom | SaleSequence | 1 | 阿拉巴马州 | 2 | 1
---|---|---|
明尼苏达州 | 1 | |
弗吉尼亚 | 3 |
您可以使用last_value
。默认范围是RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
,因此需要显式指定子句。
SELECT SaleNo, SaleSequence, SaleFrom,
last_value(SaleFrom) over(partition by SaleNo order by SaleSequence RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) SaleTo
FROM SequenceOrderSource;
在这种情况下,另一种方法是使用CROSS APPLY。像这样的代码:
SELECT SaleNo, SaleSequence, SaleFrom, OrderData.SaleFrom AS SaleTo
CROSS APPLY (SELECT TOP 1 SaleFrom FROM SequenceOrderSource
ORDER BY SaleSequence DESC) OrderData
FROM SequenceOrderSource;