sql - 多个 CTE where 子句引用 CTE 列

标签 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 吗。

我收到以下错误:

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/

相关文章:

c# - 将 Form1 文本框值传递给 Form2 按钮

sql-server - 在 ADO.NET 中使用 SQLXML,谁需要处理?

sql - T-SQL 中的首选序列算法

sql - 行数据之间的划分 - SQL

java - JDBI中如何动态绑定(bind)一个表名

c# - 从 SQL Server 检索图像并使用 C# 在 WPF 网格中显示

sql - 如何从变量运行超过 8000 个字符的 SQL 语句?

SQL Server SELECT 到 JSON 函数

sql - 如何在 SQL Server 中使用 AXSD?

mysql - mysql for Postgresql 中熟悉的PATINDEX函数