将相关子查询重写为 CROSS APPLY
Rewrite correlated subquery to CROSS APPLY
所以我正在尝试使用 CROSS APPLY
但似乎无法正确使用它。
我有一些类似这样的查询:
SELECT COL1, COL2
FROM dbo.tableA AS A
WHERE COL3 = (SELECT MAX(COL4)
FROM dbo.tableA AS B
WHERE A.COL1 = B.COL1) AS SUB
我试试这个:
SELECT COL1, COL2
FROM dbo.tableA AS A
CROSS APPLY (SELECT MAX(COL4) AS MAX_DATE
FROM TABLEA AS B
WHERE A.COL1 = B.COL1) AS SUB
但是当我使用 CROSS APPLY
时,我总是 return 多行。我的错误在哪里?
您在第二个查询中遗漏了 WHERE
,如果您希望这两个查询相同:
SELECT COL1, COL2
FROM dbo.tableA AS A
CROSS APPLY (SELECT MAX(COL4) AS MAX_DATE
FROM TABLEA AS B
WHERE A.COL1 = B.COL1) AS SUB
WHERE A.COL3 = SUB.MAX_DATE;
除了 APPLY
重写之外,因为这是一个自连接,所以它也可以通过 MAX
window 聚合来完成:
SELECT COL1, COL2
FROM (
SELECT *,
MAX(COL4) OVER (PARTITION BY COL1) AS mx
FROM dbo.tableA
) AS A
WHERE COL3 = mx
所以我正在尝试使用 CROSS APPLY
但似乎无法正确使用它。
我有一些类似这样的查询:
SELECT COL1, COL2
FROM dbo.tableA AS A
WHERE COL3 = (SELECT MAX(COL4)
FROM dbo.tableA AS B
WHERE A.COL1 = B.COL1) AS SUB
我试试这个:
SELECT COL1, COL2
FROM dbo.tableA AS A
CROSS APPLY (SELECT MAX(COL4) AS MAX_DATE
FROM TABLEA AS B
WHERE A.COL1 = B.COL1) AS SUB
但是当我使用 CROSS APPLY
时,我总是 return 多行。我的错误在哪里?
您在第二个查询中遗漏了 WHERE
,如果您希望这两个查询相同:
SELECT COL1, COL2
FROM dbo.tableA AS A
CROSS APPLY (SELECT MAX(COL4) AS MAX_DATE
FROM TABLEA AS B
WHERE A.COL1 = B.COL1) AS SUB
WHERE A.COL3 = SUB.MAX_DATE;
除了 APPLY
重写之外,因为这是一个自连接,所以它也可以通过 MAX
window 聚合来完成:
SELECT COL1, COL2
FROM (
SELECT *,
MAX(COL4) OVER (PARTITION BY COL1) AS mx
FROM dbo.tableA
) AS A
WHERE COL3 = mx