如何通过将两个CTE与不同的表相结合来获得理想的结果?

时间:2017-05-03 08:01:21

标签: sql-server sql-server-2008 sql-server-2008-r2

我有两个CTE,首先是

  ;WITH CTE AS (SELECT A.* 
                    , Row_NUMBER() Over (Partition by ID order by Date asc) RN 
             FROM TABLE A)
    SELECT Sum(Weight) as IN_WT
    FROM CTE 
    WHERE RN = 1 and name='dev1'

然后

 ;WITH CTE AS (SELECT B.* 
                    , Row_NUMBER() Over (Partition by ID order by Date desc) RN1 
             FROM TABLE B)
    SELECT Sum(Weight) AS out_wt
    FROM CTE 
    WHERE RN1 = 1 and name='dev1'

这里我们有两个tableTableA,TableB。我们从TableA得到In_wt,从TableB得到Out_wt.Now我有一个要求输出应该合并并从不同的表和同一个名字得到单行的in_wt,out_wt。我试过结合CTE,但没有得到理想的结果。我们怎么做?

1 个答案:

答案 0 :(得分:2)

试试这个:

 ;WITH CTE1 AS (
     SELECT name, 
            Row_NUMBER() Over (Partition by ID order by Date asc) RN 
     FROM TABLEA
 ), CTE2 AS (
     SELECT name, 
            Row_NUMBER() Over (Partition by ID order by Date desc) RN
     FROM TABLEB
 )
 SELECT (SELECT Sum(Weight) FROM CTE1 WHERE RN = 1 and name='dev1') AS IN_WT,
        (SELECT Sum(Weight) FROM CTE2 WHERE RN = 1 and name='dev1') AS OUT_WT