I need a query
A have 2 tables invoice en payments
Invoice: Number name amount write-off etc.
Payment sales (Boolean) debit(amount) credit(amount) etc.
I need a list with only the invoices which are not fully paid
Select * from invoice
left outer join payments on invoice.ID=payments.id
Where year(date)=2013 and amount sum(credit where payments.sales)+sum(debit where payments.sales)-write-off <>0
, Sum(debit) As debit
, Sum(credit) As credit
WHERE d_cinvoice = 1
AND payed = 0
) As payments_so_far
ON payments_so_far.invoiceid = invoice.invoiceid
I've taken step 1 and made it a subquery (wrapped it in brackets, given it al alias) then joined this to your invoice table.