I have an invoices and a payments table.
For each invoice record (which contains an OriginalInvoiceValue field), there can be multiple payments associated in the payments table. In a select that joins the two tables, each invoice record is of course repeated for each occurrence of an associated payment record.
What I would like though, is to have the OriginalInvoiceValue field returned only once per invoice, and then have it return 0 (or NULL) for each additional occurrence of an associated payment record. (Such that if I were to export the data to excel and sum the OriginalInvoiceValue column, I actually get the real total of all invoices, instead of getting it multiplied by each additional occurrence of a payment).
Is this possible in T-SQL?
If Sql Server 2005 or newer, you might assign row numbers to individual payments of an invoice, and left join to invoices selecting actual invoice record for first payment only. Put order by you require in
row_number()part; I’ve chosen PaymentID, but payment date is probably more appropriate.And here is SQL FIDDLE with example.