我们可以在CROSS APPLY中加入表吗?

时间:2015-10-27 12:01:01

标签: sql sql-server-2008 join common-table-expression

我的查询是:

CROSS APPLY(
SELECT SUM(Payment)
FROM (
    SELECT TOP(ABS(2)) Payment 
    FROM dbo.table1 
) AS T
) AS EC(ExpCalc)

加入后我需要这样的东西:

CROSS APPLY(
SELECT SUM(Payment)
FROM (
    SELECT TOP(ABS(2)) Payment 
    FROM dbo.table1 t1
) AS T
) AS EC(ExpCalc) JOIN dbo.info i on t1.key = i.key 

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

首先,你不能做你想做的事,因为你没有回归key。但更大的答案是你可以做一个join,但你可以做一个相关的子查询:

CROSS APPLY
(SELECT SUM(Payment)
 FROM (SELECT TOP(ABS(2)) Payment 
       FROM dbo.table1 t1
       WHERE t1.key = i.key
------^
      ) T
) AS EC(ExpCalc) 

这会出现在这样的FROM子句中:

FROM dbo.info i CROSS APPLY
(SELECT SUM(Payment)
 FROM (SELECT TOP(ABS(2)) Payment 
       FROM dbo.table1 t1
       WHERE t1.key = i.key
      ) T
) AS EC(ExpCalc)