上一条与下一条的取值
如果您想把某一列的值上移或下移 1 行该怎么办?您可以复用上一练习的步骤,但要用到两个新函数:LEAD()(下一条的值)和 LAG()(上一条的值)。步骤如下:
- 先创建分区;
- 然后按某一列排序;
- 最后根据需要使用
LEAD()和/或LAG()函数。
本练习是课程的一部分
SQL Server 中级
练习说明
- 编写一条 T-SQL 查询,对每个销售区域:
- 将
OrderDate的值下移 1 行。将该列命名为PreviousOrder。 - 将
OrderDate的值上移 1 行。将该列命名为NextOrder。 您需要按 territory 进行 PARTITION BY
- 将
交互式实操练习
通过完成这段示例代码来试试这个练习。
SELECT TerritoryName, OrderDate,
-- Specify the previous OrderDate in the window
___(OrderDate)
-- Over the window, partition by territory & order by order date
___(___ BY ___ ___ BY ___) AS PreviousOrder,
-- Specify the next OrderDate in the window
___(OrderDate)
-- Create the partitions and arrange the rows
___ AS NextOrder
FROM Orders