我想加入一个包含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
我做错了什么?
答案 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