一种比在最终 SELECT 中将 IB 表加入到“cte”更复杂的方法是使用当前表作为表嵌套另一个 CTE。例如:
;WITH cte AS
(
SELECT IJLOC, IJITEM, IJDATE, IJLCGT,
rn = ROW_NUMBER() OVER (PARTITION BY IJITEM, IJLOC ORDER BY IJDATE DESC)
FROM dbo.IJ
),
filtered AS (
SELECT IJLOC, IJITEM, IJDATE, IJLCGT
FROM cte
WHERE rn = 1
)
SELECT ib.QOO, ib.QOH, ib.QCM, ib.[AVG]
FROM ib
INNER JOIN filtered
ON filtered.IJITEM = IB.IBITEM
AND filtered.IJLOC = IB.IBLOC
另一种选择,取决于查询优化器如何处理所有表之间的 JOIN,如果您不需要从 IJ 表中返回任何字段,则将 CTE 的结果插入到临时表中,然后 JOIN到那个。例如:
CREATE TABLE #Temp (IJITEM DataType, IJLOC DataType)
;WITH cte AS
(
SELECT IJLOC, IJITEM, IJDATE, IJLCGT,
rn = ROW_NUMBER() OVER (PARTITION BY IJITEM, IJLOC ORDER BY IJDATE DESC)
FROM dbo.IJ
)
INSERT INTO #Temp (IJITEM, IJLOC)
SELECT IJITEM, IJLOC
FROM cte
WHERE rn = 1;
SELECT ib.QOO, ib.QOH, ib.QCM, ib.[AVG]
FROM ib
INNER JOIN #Temp tmp
ON tmp.IJITEM = IB.IBITEM
AND tmp.IJLOC = IB.IBLOC