How to get desired result by combining two CTE's?

◇◆丶佛笑我妖孽 提交于 2019-12-12 06:03:26

问题


I have two CTE's,firstly

  ;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'

and then

 ;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'

Now I had a reuiremnt that the output should be combined and get in_wt,out_wt.I tried combining both the CTE's but didn't get the desired result.How can we do that?


回答1:


If both CTEs access the same table, as implied by the queries in the question, then you can use the following query to get the expected result:

;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'



回答2:


You have 2 tables and there is not any relation between them. Then combine 2 query simply like that

;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



回答3:


This was the simple Solution I Found,

A 'quick & dirty' approach would be two wrap your queries in two other CTE's SELECT (SELECT IN_WT FROM CTE1), (SELECT OUT_WT FROM CTE2)



来源:https://stackoverflow.com/questions/43753515/how-to-get-desired-result-by-combining-two-ctes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!