We have a table of payments associated with an "agent".
tblPayment:
AgentID PaymentID Amount AdjustmentID
30101 10001 $40.00 701
30101 10002 $50.00 902
30101 10003 $50.00 902
30101 10004 $50.00 902
30101 10005 $60.00 844
There should be only one payment for each "AdjustmentID" value, however we've discovered multiple payments applied to the same "AdjustmentID" (see Payments 1002, 1003, and 1004).
I need to run a special report to show how these duplicates have screwed up our data.
EXAMPLE #1:
I can do this one easily enough...
AgentID= 30101
SUM(Amount)= $250
SUM(duplicates)= $150
CORRECTED_VALUE = $250 - $150 = $100 (wrong)
Using:
SELECT SUM(a.Amount) FROM tblPayment a WHERE EXISTS
(SELECT b.AdjustmentID, b.Amount, count(*)
FROM tblPayment b
WHERE a.AdjustmentID = b.AdjustmentID AND
a.Amount = b.Amount AND b.AgentID = 30101
GROUP BY b.AdjustmentID, b.Amount HAVING count(*) > 1 )
However, when you subtract the duplicate sum from the total sum, you get $100 which is not the correct value. This is not what I need because removing all of the duplicates also removes the one correct payment (payment_id= 10002).
What I want is:
METHOD #1:
AgentID= 30101
Sum(Amount) = $250
Sum(duplicates) = $100 (with correct first payment not included)
CORRECT = $250 - $100 = $150
or
METHOD #2:
AgentID= 30101
Sum(Amount) = $250
Sum(duplicates) = $150
Sum(distinct_duplicate) = $50.00 (replacing the correct first payment)
CORRECT = $250 - $150 + $50 = $150
QUESTION: Can anyone figure out how to leave one payment in the summation (for method #1)
or create a whole different SQL statement to return the payment amount of each distinct AdjustmentID ONLY if duplicate payments were made on that AdjustmentID (for method #2).