SQL Server:连接包含WITH子句的派生表?

时间:2010-04-21 16:36:06

标签: sql-server subquery row-number derived-table

我想加入一个包含WITH子句的子查询/派生表(必须使用WITH子句来过滤ROW_NUMBER() = 1)。在Teradata中,类似的东西可以正常工作,但Teradata使用QUALIFY ROW_NUMBER() = 1而不是WITH子句。

以下是我对此次加入的尝试:

-- want to join row with max StartDate on JobModelID
INNER JOIN (
    WITH AllRuns AS (
        SELECT *,
            ROW_NUMBER() OVER (PARTITION BY JobModelID ORDER BY StartDate DESC) AS RowNumber
        FROM Runs
    )
    SELECT * FROM AllRuns WHERE RowNumber = 1
) Runs
ON JobModels.JobModelID = Runs.JobModelID

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以使用多个WITH子句。像

这样的东西
;WITH AllRuns AS ( 
        SELECT  *, 
                ROW_NUMBER() OVER (PARTITION BY JobModelID ORDER BY StartDate DESC) AS RowNumber 
        FROM    Runs 
),
Runs AS(
        SELECT  * 
        FROM    AllRuns 
        WHERE   RowNumber = 1
)

SELECT  *
FROM    ... INNER JOIN ( 
        Runs ON JobModels.JobModelID = Runs.JobModelID 

有关用法/结构/规则的更多详细信息,请参阅WITH common_table_expression (Transact-SQL)

答案 1 :(得分:0)

添加连接条件可能效率较低,但通常对我来说效果很好。

INNER JOIN (
    SELECT *,
           ROW_NUMBER() OVER 
           (PARTITION BY JobModelID 
           ORDER BY StartDate DESC) AS RowNumber
      FROM Runs
    ) Runs
ON JobModels.JobModelID = Runs.JobModelID 
AND Runs.RowNumber = 1