多个CTE where子句引用CTW列

时间:2019-01-18 04:07:53

标签: sql sql-server tsql sql-server-2012

例如

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。

我收到以下错误:

  

找不到标识符“ UserDetail.UserId”的多个部分

在CTE参考中,是否可以在不加入CTE表的情况下引用回先前的CTE?还是我写错了查询

1 个答案:

答案 0 :(得分:3)

您可以这样使用-加入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)
    )