例如
WITH UserDetail (UserId, UserName)
AS
(
SELECT TOP(10) U.UserId,U.UserName
FROM UserTable U
),
UserAction (ActionName,ActionType)
AS
(
SELECT TOP(10) A.ActionName,A.ActionType
FROM ActionTable A
WHERE A.UserId = UserDetail.UserId // Is it possible to direct reference
)
WHERE A.UserId = UserDetail.UserId
我可以直接执行此操作而不是在我的第二个 CTE 中加入 UserDetail 吗。
我收到以下错误:
multi-part of identifier "UserDetail.UserId" could not be found
在 CTE 引用中,是否可以在不加入 CTE 表的情况下引用以前的 CTE?或者我写了一个错误的查询
最佳答案
你可以像这样使用 - 加入 UserDetail
cte
WITH UserDetail (UserId, UserName)
AS
(
SELECT TOP(10) U.UserId,U.UserName
FROM UserTable U
),
UserAction (ActionName,ActionType)
AS
(
SELECT TOP(10) A.ActionName,A.ActionType
FROM ActionTable A inner join UserDetail
on A.UserId = UserDetail.UserId
)
或者你可以使用子查询
WITH UserDetail (UserId, UserName)
AS
(
SELECT TOP(10) U.UserId,U.UserName
FROM UserTable U
),
UserAction (ActionName,ActionType)
AS
(
SELECT TOP(10) A.ActionName,A.ActionType
FROM ActionTable A
where A.UserId in (select UserDetail.UserId from UserDetail)
)
关于sql - 多个 CTE where 子句引用 CTE 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54247632/