查询从两个不同的表中求和

时间:2016-12-19 05:26:07

标签: sql-server

enter image description here

我有两张桌子:

表1:ORK3

+-------------+
| k3  k1      |
+-------------+
| 1   a       |
| 4   b       |
| 5   c       |
| 3   a       |
+-------------+         

表2:ORK2

+------+----+
|  k11 | k1 |
+------+----+
|    2 | a  |
|    3 | b  |
|    4 | c  |
|    7 | a  |
|    3 | a  |
|    1 | b  |
+------+----+                   

结果

    k1    sum(k3)  sum(k11)   (sumk3-sumk11)
    a       11          4        7
    b        4          4         0
    c        4          5         -1

我希望sum(sumk3-sumk11)中的值null不出现在查询中

我正在尝试这种方式

SELECT 
    COALESCE(ORK2_RESULT.K1, ORK3_RESULT.K12) AS K1,
    ORK2_RESULT.SUM_K11 AS SUM_K11,
    ORK3_RESULT.SUM_K3 AS SUM_K3
FROM 
    (SELECT 
         K1 AS K1, SUM(K11) AS SUM_K11
     FROM 
         ORK2
     GROUP BY 
         K1) AS ORK2_RESULT
FULL OUTER JOIN 
    (SELECT 
         K1 AS K12, SUM(K3) AS SUM_K3
     FROM 
         ORK3
     GROUP BY 
         K1) AS ORK3_RESULT ON ORK2_RESULT.K1 = ORK3_RESULT.K12

2 个答案:

答案 0 :(得分:1)

     ;WITH ork3(k3,k1)  AS (     

        SELECT 1,'a' UNION       
        SELECT 4,'b' UNION              
        SELECT 5,'c' UNION              
        SELECT 3,'a'               
    ),ork2 (k11,k1)  AS (
        SELECT 2,'a' UNION
        SELECT 3,'b' UNION
        SELECT 4,'c' UNION
        SELECT 7,'a' UNION
        SELECT 3,'a' UNION
        SELECT  1,'b'
    )
    SELECT ISNULL(a.k1,b.k1),a.k3,b.k11 ,ISNULL(a.k3,0)-ISNULL(b.k11 ,0)
    FROM (
      SELECT ork3.k1,SUM(ork3.k3) AS k3 FROM ork3 GROUP BY ork3.k1) AS a
      FULL JOIN (
        SELECT ork2.k1,SUM(ork2.k11) AS k11 FROM ork2 GROUP BY ork2.k1
      ) AS b ON a.k1=b.k1
     k3          k11         
---- ----------- ----------- -----------
a    4           12          -8
b    4           4           0
c    5           4           1

答案 1 :(得分:0)

我用这个

SELECT COALESCE(ORK2_RESULT.K1, ORK3_RESULT.K12) AS K1
, ORK2_RESULT.SUM_K11 AS SUM_K11
, ORK3_RESULT.SUM_K3 AS SUM_K3
FROM (
    SELECT K1 AS K1, SUM(K11) AS SUM_K11
    FROM ORK2
    GROUP BY K1
    ) AS ORK2_RESULT
FULL OUTER JOIN (
    SELECT K1 AS K12, SUM(K3) AS SUM_K3
    FROM ORK3
    GROUP BY K1
    ) AS ORK3_RESULT ON ORK2_RESULT.K1 = ORK3_RESULT.K12

但我不能查询sumk3-sumk11