如何通过结合两个CTE来获得理想的结果?

时间:2017-05-03 07:14:49

标签: 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'

现在我有一个要求输出应该合并并获得in_wt,out_wt的重新计算。我尝试将CTE结合起来但没有得到所需的结果。我们怎么能这样做?

3 个答案:

答案 0 :(得分:0)

如果两个CTE都访问相同的表,如问题中的查询所暗示的那样,那么您可以使用以下查询来获得预期结果:

;WITH CTE AS (
   SELECT *, 
          Row_NUMBER() Over (Partition by ID order by Date asc) RN1,
          Row_NUMBER() Over (Partition by ID order by Date desc) RN2
   FROM TABLE
)
SELECT SUM(CASE WHEN RN1 = 1 THEN Weight ELSE 0 END) as IN_WT,
       SUM(CASE WHEN RN2 = 1 THEN Weight ELSE 0 END) as OUT_WT
FROM CTE 
WHERE 1 IN (RN1, RN2) AND name = 'dev1'

答案 1 :(得分:0)

你有2个表,它们之间没有任何关系。 然后简单地结合2个查询

;WITH cteA AS (SELECT A.* 
                , Row_NUMBER() Over (Partition by ID order by Date asc) RN 
          FROM TABLEA A),
         cteB AS (SELECT B.* 
                , Row_NUMBER() Over (Partition by ID order by Date desc) RN
          FROM TABLEB B)
SELECT 
      (   SELECT Sum(Weight) 
         FROM cteA 
         WHERE RN = 1 and name='dev1'
      ) as IN_WT,
      (   SELECT Sum(Weight) 
         FROM cteB 
         WHERE RN = 1 and name='dev1'
      ) as OUT_WT

答案 2 :(得分:0)

这是我找到的简单解决方案,

'快速&脏'的方法是将你的查询包装在另外两个CTE的SELECT (SELECT IN_WT FROM CTE1), (SELECT OUT_WT FROM CTE2)