I have 2 tables in which I need a query, and return a result set of "exceptions" based on whether the sum of the field in table1 is equal to the sum of the field in table2 (where the other columns match).
select A.TranName,A.TranDate,A.TranCode,SUM(A.TranQty) AS T1Qty,B.TranName,B.TranDate,B.TranCode,SUM(B.TranQty) AS T2Qty from Table1 AS A LEFT JOIN Table2 AS B on A.TranName = B.TranName AND A.TranDate = B.TranDate AND A.TranCode = B.TranCode GROUP BY A.TranName, A.TranDate, A.TranCode, B.TranName, B.TranDate, B.TranCode HAVING SUM(A.TranQty) != SUM(B.TranQty)
The result set is incorrect because it multiplies the sum of Table1.TranQty by the number of rows returned from table 2.
For example, if in table 1 there was 1 record in which the connection was mapped to 2 records in table 2, the TranQty of 1 record in table 1 would be multiplied by 2 (and, accordingly, mapped incorrectly).
I am sure that I am missing something in common in using the aggregate function (sum) in the left join.
Thanks for the help!
(System is MSSql)
source share