开始使用免费开始使用

上一条与下一条的取值

如果您想把某一列的值上移或下移 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
编辑并运行代码