gpt4 book ai didi

sql - 希望通过左外连接将数据添加到查询中而不重复

转载 作者:行者123 更新时间:2023-12-03 03:38:40 26 4
gpt4 key购买 nike

我有一个数据库结构(下面的 ER 图),它具有三级分层数据和第四级可选数据。 enter image description here

如果我编写一个查询来获取三个级别(级别 1 到级别 3)的非规范化数据,其中三个表中的示例数据如下所示:

enter image description here

查询时,这种数据布局非常简单,如下所示:

enter image description here

运行以下查询后,我得到以下输出(并且我尝试了各种组合,将 L1 集合组合到 L4 并将一个 L4 移出作为另一个查询,然后加入 L1 - L4 集合等)-这又符合预期。

SELECT        [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId, 
ManagementResponse.ManagementResponseTest
FROM Category INNER JOIN
[Group] ON Category.GroupId = [Group].GroupId INNER JOIN
RLI ON Category.CategoryId = RLI.CategoryId LEFT OUTER JOIN
ManagementResponse ON RLI.RLIId = ManagementResponse.RLIId LEFT OUTER JOIN
Comment ON RLI.RLIId = Comment.RLIId

enter image description here

但是,我需要以下格式的数据 - 这是我无法弄清楚如何获取的(当我通过左侧添加额外的 4 级数据时,我不希望 4 级数据重复外连接): enter image description here

最佳答案

此查询将为您提供最终输出: enter image description here

WITH CommentAndResponse AS (

SELECT Comment.CommentId,
Comment.CommentText,
ManagementResponse.ManagementResponseId,
ManagementResponse.ManagementResponseTest,
COALESCE(Comment.RLIId, ManagementResponse.RLIId) AS RLIId
FROM (
(SELECT Comment.CommentId,
Comment.CommentText,
Comment.RLIId,
ROW_NUMBER() OVER (PARTITION BY Comment.RLIId ORDER BY Comment.CommentId) AS CommentRowNumber
FROM Comment) AS Comment
FULL JOIN
(SELECT ManagementResponse.ManagementResponseId,
ManagementResponse.ManagementResponseTest,
ManagementResponse.RLIId,
ROW_NUMBER() OVER (PARTITION BY ManagementResponse.RLIId ORDER BY ManagementResponse.ManagementResponseId) AS ManagementResponseRowNumber
FROM ManagementResponse) AS ManagementResponse
ON Comment.CommentRowNumber = ManagementResponse.ManagementResponseRowNumber AND Comment.RLIId = ManagementResponse.RLIId )
)

SELECT [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, CommentAndResponse.CommentId, CommentAndResponse.CommentText, CommentAndResponse.ManagementResponseId, CommentAndResponse.ManagementResponseTest
FROM [Category]
INNER JOIN [Group] ON Category.GroupId = [Group].GroupId
INNER JOIN [RLI] ON Category.CategoryId = RLI.CategoryId
LEFT OUTER JOIN [CommentAndResponse] ON RLI.RLIId = CommentAndResponse.RLIId

关于sql - 希望通过左外连接将数据添加到查询中而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com