gpt4 book ai didi

sql - T-SQL JOIN针对公用表表达式(CTE)

转载 作者:行者123 更新时间:2023-12-03 13:12:24 28 4
gpt4 key购买 nike

是否可以对通用表表达式执行JOIN子查询?如果不是,那么有人可以让我知道如何执行我在下面尝试做的事情吗?例子将是极好的。

例如:

LEFT JOIN (

;WITH [UserDefined]
AS (SELECT *, -- Make sure we get only the latest revision.
ROW_NUMBER() OVER (PARTITION BY [ID]
ORDER BY [RevisionNumber] DESC) AS RN
FROM [syn_Change])

SELECT [UserDefined].[ID]
,[UserDefined].[ChangeNumber]
,[UserDefined].[Usr_CoResponsibility]
,[UserDefined].[Usr_StarFlowStatus]

FROM [UserDefined]
WHERE (RN = 1)

) [UserColumns]
ON [UserColumns].[ChangeNumber] = [CTE].[ChangeNumber]

这是我的完整查询:
;WITH CTE
AS (SELECT *, -- Make sure we get only the latest revision.
ROW_NUMBER() OVER (PARTITION BY [ItemID]
ORDER BY [RevisionNumber] DESC) AS RN
FROM [dw_Change])

SELECT [CTE].[ItemID]
,[CTE].[ViewID]
,[CTE].[FolderItemID]
,[CTE].[RevisionNumber]
,[CTE].[ChangeNumber]
,[CTE].[Synopsis]
,[CTE].[Description]
,[CTE].[EnteredOn]
,[CTE].[Responsibility]
--,[UserColumns].[Usr_CoResponsibility]
--,[UserColumns].[Usr_StarFlowStatus]
,[CTE].[Status] -- This will display the human name on the front-end with code.
,[Users].[F7] AS [ResponsibilityName]
,[GroupName].[Name] AS [AppGroupName]
,[AppName].[Name] AS [AppName]
FROM CTE
LEFT JOIN [S3] [Users] ON [Users].[F0] = [CTE].[Responsibility]
LEFT JOIN (SELECT [Name], [ViewID]
FROM [dw_Folder]
WHERE ([FolderItemID] = -1)) [GroupName]
ON [GroupName].[ViewID] = [CTE].[ViewID]

LEFT JOIN (SELECT [Name], [ItemID]
FROM [dw_Folder]
WHERE ([FolderItemID] <> -1)) [AppName]
ON [AppName].[ItemID] = [CTE].[FolderItemID]

LEFT JOIN (

;WITH [UserDefined]
AS (SELECT *, -- Make sure we get only the latest revision.
ROW_NUMBER() OVER (PARTITION BY [ID]
ORDER BY [RevisionNumber] DESC) AS RN
FROM [syn_Change])

SELECT [UserDefined].[ID]
,[UserDefined].[ChangeNumber]
,[UserDefined].[Usr_CoResponsibility]
,[UserDefined].[Usr_StarFlowStatus]

FROM [UserDefined]
WHERE (RN = 1)

) [UserColumns]
ON [UserColumns].[ChangeNumber] = [CTE].[ChangeNumber]

WHERE (RN = 1)

非常感谢!

最佳答案

定义CTE时,您要先执行其余查询。所以你不能写:

LEFT JOIN (
;WITH CTE
...
)

顺便说一句, 的原因是人们将 ;放在 WITH前面是因为所有先前的语句都需要终止。如果开发人员可以养成用 ;终止所有SQL语句的习惯,则没有必要,但是我离题了...

您可以像这样编写多个CTE:
WITH SomeCTE AS (
SELECT ...
FROM ...
), AnotherCTE AS (
SELECT ...
FROM ...
)
SELECT *
FROM SomeCTE LEFT JOIN
AnotherCTE ON ...
;

关于sql - T-SQL JOIN针对公用表表达式(CTE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8403339/

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