左连接到Row_Number = 1的子查询

时间:2018-03-15 22:16:43

标签: sql-server tsql left-join window-functions row-number

我真是太蠢了!处理下面方案的最佳方法是什么? ID 27并不存在于SuperRadSubQuery中,但它确实存在于WayCoolLeftTable中。如果我运行整个查询,它不会返回任何内容。如果我在最后一行排除AND,则返回一行。这绝对不是我的预期,我很惊讶我的WHERE过滤器是"腐败"我的LEFT JOIN。我更喜欢不使用临时表。我可以改为MAX,但那也是愚蠢的吗?提前谢谢!

SELECT *
    FROM WayCoolLeftTable a
    LEFT JOIN
                (
                    SELECT   ROW_NUMBER() OVER (PARTITION BY ID ORDER BY SourceDate DESC) AS RowNumber
                            ,ID
                            ,SourceDate
                    FROM SuperRadSubQuery
                ) b
            ON a.ID = b.ID
WHERE a.ID = 27
AND b.RowNumber = 1

1 个答案:

答案 0 :(得分:2)

第二个表格中的条件位于on子句:

SELECT *
FROM WayCoolLeftTable a LEFT JOIN
     (SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY SourceDate DESC) AS RowNumber,
            ID, SourceDate
      FROM SuperRadSubQuery
     ) b
     ON a.ID = b.ID and b.RowNumber = 1
WHERE a.ID = 27;

否则,外部联接变为inner join

使用横向连接,SQL Server提供了一种更有效的方法。代码如下:

SELECT *
FROM WayCoolLeftTable a OUTER APPLY
     (SELECT *  -- or whatever columns you want
      FROM SuperRadSubQuery
      WHERE a.ID = b.ID
      ORDER BY SourceDate DESC
     ) b
WHERE a.ID = 27;