简体   繁体   中英

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 .

IE
TBL1.AK(1).TOT1 = 100 == TBL2.AK(1).sum(TOT1) = 100 which is correct
TBL1.AK(2).TOT2 = 200 == TBL2.AK(2).sum(TOT2) = 150 which is wrong.

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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