declare @run_date DATETIME
select @run_date = '2016/02/19'
SELECT payment_id, Total = SUM(amount)
INTO #pym1
FROM PAYMENT_LINE
WHERE alloc_date IS NOT NULL
AND alloc_date < @run_date
AND (reversal_date <= @run_date or reversal_date IS NULL)
GROUP by payment_id
SELECT PAYMENT.payment_id, PAYMENT.payment_amount, Total
INTO #pym2
FROM PAYMENT,#pym1
WHERE PAYMENT.payment_id = #pym1.payment_id
AND Total > PAYMENT.payment_amount
SELECT payment_id, Difference_payment = (Total - payment_amount)
INTO #pym3
FROM #pym2
SELECT DEBTOR.manufacturer_id, DEBTOR.debtor_id, alloc_date, PAYMENT.payment_id, PAYMENT.payment_amount, Total,Difference_payment
FROM PAYMENT,DEBTOR, #pym2,#pym3,PAYMENT_LINE
WHERE PAYMENT.payment_id = DEBTOR.debtor_id
AND PAYMENT_LINE.payment_id = PAYMENT.payment_id
AND DEBTOR.debtor_id = PAYMENT.payment_id