简体   繁体   English

比较两个具有相同列名但具有汇总的表

[英]Compare two tables with same column name but with aggregate

I am trying to achieve this. 我正在努力实现这一目标。

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

My main table is TBL1 , and is connected with AK first, I need to sum all TBL2 's AK then compare it to TBL1 . 我的主表是TBL1 ,并且首先与AK连接,我需要对所有TBL2的AK求和,然后将其与TBL1进行比较。

IE IE浏览器
TBL1.AK(1).TOT1 = 100 == TBL2.AK(1).sum(TOT1) = 100 which is correct TBL1.AK(1).TOT1 = 100 == TBL2.AK(1).sum(TOT1) = 100是正确的
TBL1.AK(2).TOT2 = 200 == TBL2.AK(2).sum(TOT2) = 150 which is wrong. TBL1.AK(2).TOT2 = 200 == TBL2.AK(2).sum(TOT2) = 150这是错误的。

I need to get return the not equal columns 我需要返回不相等的列

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

--Assumed that TBL2 is already totaled.

I already tried this: 我已经尝试过了:

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 ....

It returns t1.AK and summed of t2.TOT1 and t2.TOT2 but not the t1.TOT1 and t1.TOT2 . 它返回t1.AK并与t2.TOT1t2.TOT2之和,但不t1.TOT1t1.TOT2

Update : 更新:
I already tried this as of now 到目前为止我已经尝试过了
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)

It returns me "00979. 00000 - "not a GROUP BY expression"" 它返回我“00979。00000-“不是GROUP BY表达式””

Aggregate before doing the join: 在进行加入之前汇总:

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;

Edit:Added t2. 编辑:添加了t2。 at last line to remove column ambiguity 在最后一行删除列的歧义

 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM