sql-server - 试图让分区中的滞后以显示以前的值
问题描述
我试图在某个分区中获取先前的值。
我试图做一个 Lag Partition over 子句,它仍然给我 NULL。
解决方案
LAG 是 MS SQl Server 2012 中引入的出色窗口功能。 https://docs.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-2017
DECLARE @Table TABLE (BusinessEntityID int, SalesYear int, SalesQuota decimal);
INSERT INTO @Table (BusinessEntityID, SalesYear, SalesQuota)
VALUES
(275,2005,367000)
,(275,2005,556000)
,(275,2006,502000)
,(275,2006,550000)
,(275,2006,1429000)
,(275,2006,1324000);
SELECT BusinessEntityID, SalesYear AS SalesYear, SalesQuota AS CurrentQuota,
LAG(SalesQuota, 1,0) OVER (ORDER BY SalesYear) AS PreviousQuota
FROM @Table
WHERE BusinessEntityID = 275 and SalesYear IN ('2005','2006');
执行查询的结果:
BusinessEntityID SalesYear CurrentQuota PreviousQuota
275 2005 367000 0
275 2005 556000 367000
275 2006 502000 556000
275 2006 550000 502000
275 2006 1429000 550000
275 2006 1324000 1429000
推荐阅读
- python - Python声明文件对象但不打开文件
- jenkins-pipeline - pipelineTriggers 的正确语法
- azure - Azure 功能管理器功能切换以在运行时评估使用标签
- node.js - 使用 admin.database.serverValue.increment 时 Firebase-admin Node.js SDK 失败
- amazon-web-services - 调用 AWS API Gateway Private 无法从 Front 访问,但 EC2 有效
- javascript - 每“x”秒从列表中显示一个新的随机单词的脚本
- azure-devops - 使用 Azure 管道秘密变量在构建代理上设置环境变量
- python - 如何在 GPU 上的数组上运行 expit 函数?
- javascript - 在自动高度尺寸上使用 CSS 过渡
- php - 使关联数组键值成为索引