【问题标题】:Multiple CTE where clauses referece CTW column多个 CTE where 子句引用 CTE 列
【发布时间】:2019-01-18 04:07:52
【问题描述】:

例如

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?或者我写错了查询

【问题讨论】:

  • 你是在做 IN 吗?当您尝试在具有多个值而不加入的表上执行此操作时,我不明白您希望如何执行=。你为什么不加入就尝试这样做?
  • @Ben 想知道是否有任何替代方法而不是加入表格。
  • UserDetail 中最多有 10 行。 行的UserId 您要引用吗?你现在明白你为什么想要/需要加入了吗?

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


【解决方案1】:

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

【讨论】:

  • 不加入也可以吗?
  • 不,不加入是不可能的,但你可以使用子查询来引用这个 - 但直接不可能@abccba
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
相关资源
最近更新 更多