比较具有相同列名但具有聚合的两个表

时间:2015-11-11 01:46:41

标签: sql oracle join aggregate

我正在努力实现这一目标。

TBL 1  
PK   AK   TOT1   TOT2  
1    1    100    100  
2    2    200    200


TBL 2  
PK   AK   TOT1   TOT2  
1    1     50     50  
2    1     50     50  
3    2     100    100  
4    2     50     50

我的主要表格为TBL1,并与AK相关联 首先,我需要总结所有TBL2的AK,然后将其与之进行比较 TBL1

即。
     TBL1.AK(1).TOT1 = 100 == TBL2.AK(1).sum(TOT1) = 100 这是正确的      TBL1.AK(2).TOT2 = 200 == TBL2.AK(2).sum(TOT2) = 150 这是错误的。

我需要返回不相等的列

Return TBL  
PK   AK   TBL1.TOT1   TBL2.TOT2  
2    2     200         150 

--Assumed that TBL2 is already totaled.

我已经尝试过了:

Select AK, SUM(t1.TOT1), SUM(t2.TOT2)  
FROM TBL1 t1  
JOIN TBL2 t2  
ON t1.AK = t2.AK  
GROUP BY t1.AK  
WHERE t1.TOT1 IS NOT t2.TOT2 ....

返回t1.AK并将t2.TOT1t2.TOT2相加 但不是t1.TOT1t1.TOT2

更新:
我现在已经尝试过这个了 SELECT t1.AK, sum(t2.TOT1) FROM TBL1 t1 JOIN TBL t2 ON t1.AK = t2.AK GROUP BY t1.AK HAVING t1.TOT1 <> sum(t2.TOT1)

它归还给我 &#34; 00979。 00000 - &#34;不是GROUP BY表达式&#34;&#34;

2 个答案:

答案 0 :(得分:2)

在进行加入之前进行聚合:

Select t1.AK, t1.TOT1, t2.TOT2
FROM TBL1 t1 LEFT JOIN
     (SELECT ak, SUM(TOT2) as TOT2
      FROM TBL2 t2  
      GROUP BY ak
     ) t2
     ON t1.AK = t2.AK
WHERE t1.TOT1 <> t2.TOT2 OR t2.TOT2 IS NULL;

编辑:添加了t2。在最后一行删除列歧义

答案 1 :(得分:0)

 WITH table1 AS (SELECT 1 AS ak, 100 AS tot1, 100 AS tot2 FROM dual UNION ALL
                   SELECT 2 AS ak, 200 AS tot1, 200 AS tot2 FROM dual  ),
         table2 AS (SELECT 1 AS ak, 50 AS tot1, 50 AS tot2 FROM dual UNION ALL
                  SELECT 1 AS ak, 50 AS tot1, 50 AS tot2 FROM dual UNION ALL
                  SELECT 2 AS ak, 100 AS tot1, 100 AS tot2 FROM dual UNION ALL
                  SELECT 2 AS ak, 50 AS tot1, 50 AS tot2 FROM dual )


SELECT table1.ak, table1.tot1, z.tot1 
FROM table1 JOIN
(SELECT table2.ak ak, sum(table2.tot1) tot1, sum(table2.tot2) tot2
FROM table2
GROUP By table2.ak) z ON table1.ak = z.ak
WHERE   table1.tot1 <> z.tot1 
 AND    table1.tot2 <> z.tot2;