首页 > 解决方案 > T-SQL LAG 函数默认值

问题描述

为什么 LAG 函数的默认参数只适用于返回结果的第一列,如果连接表中没有记录并且您只是引用连接表字段?

为了更好地解释这一点,我创建了以下场景。

架构

  CREATE TABLE Blogs(
    Id int IDENTITY(1,1) CONSTRAINT PK_Blogs_Id PRIMARY KEY,
    Title NVARCHAR(1000)
  )

  CREATE TABLE Comments(
    Id int IDENTITY(1,1) CONSTRAINT PK_Comments_Id PRIMARY KEY,
    BlogId INT NOT NULL,
    CommentText NVARCHAR(max)
  )

  INSERT INTO Blogs (Title) VALUES ('Blog 1')
  INSERT INTO Blogs (Title) VALUES ('Blog 2')
  INSERT INTO Blogs (Title) VALUES ('Blog 3')
  INSERT INTO Blogs (Title) VALUES ('Blog 4')
  INSERT INTO Blogs (Title) VALUES ('Blog 5')

  INSERT INTO Comments (BlogId, CommentText) VALUES (4,'Some text')
  INSERT INTO Comments (BlogId, CommentText) VALUES (4,'Some text 2')

询问

SELECT *, 
  LAG(CommentText,1,'No comment') OVER (Partition by Comments.BlogId ORDER BY Comments.Id Desc) LastComment
FROM Blogs LEFT JOIN Comments on Blogs.Id = Comments.BlogId;

在上面的查询中,它将返回第一行 LastComment 的结果为“无评论”,并且该行有其他评论,其余的将为空。

如果您在窗口函数(下面的查询)中引用 Blogs 的键,我知道它可以正常工作(所有为 null 的行在 LastComment 字段中返回“无评论”)但我试图理解为什么如果连接返回 null,为什么不在 LastComment LAG 函数中应用默认参数。

SELECT *, 
  LAG(CommentText,1,'No comment') OVER (Partition by Blogs.Id ORDER BY Comments.Id Desc) LastComment
FROM Blogs LEFT JOIN Comments on Blogs.Id = Comments.BlogId;

这是场景http://sqlfiddle.com/#!18/eb850/9的 SQL 小提琴

标签: sqltsqlwindow-functions

解决方案


推荐阅读