我必须从两个选择查询中获得结果,其中第二个查询结果以第一个查询结果为条件。
Table 1: tbl1
EndDate PEL FL
4/24/2015 2 4
6/12/2015 3 5
8/9/2015 4 7
Table 2 : tbl2
EndDate CumEL CumFL
3/20/2015 3 6
4/10/2015 2 9
4/15/2015 1 2
5/10/2015 4 1
5/21/2015 5 5
6/12/2015 8 7
6/15/2015 1 2
7/6/2015 4 1
7/11/2015 5 5
8/9/2015 8 7
我想按以下标准加入这两个表:
Select tbl1.* from tbl1
JOIN
Select Sum(CumEL),Sum(CumFL) from tbl2 where tbl2.EndDate <= tbl1.EndDate
期望的输出:
EndDate PEL FL CumEL CumFL
4/24/2015 2 4 6 17
6/12/2015 3 5 23 30
8/9/2015 4 7 41 45
答案 0 :(得分:1)
一种方法是使用交叉应用(虽然连接也可以工作,但编写起来有点复杂):
SELECT tbl1.EndDate, tbl1.PEL, tbl1.FL, C.CumEL, C.CumFL
FROM tbl1
CROSS APPLY
(
SELECT SUM(CumEL) AS CumEL, SUM(CumFL) AS CumFL
FROM tbl2
WHERE tbl2.EndDate <= tbl1.EndDate
) AS C;
答案 1 :(得分:1)
您可以像这样使用left join
select tbl1.EndDate, tbl1.PEL, tbl1.FL,
SUM(Coalesce(tbl2.CumEL,0) as CumEL,
SUM(Coalesce(tbl2.CumFL,0)) as CumFL,
from tbl1
left join tbl1 on tbl1.EndDate >= tbl2.EndDate
group by tbl1.EndDate, tbl1.PEL, tbl1.FL