AND type in (N'FN', N'IF', N'TF', N 'FS', N'FT')) /*must be*/ AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')) /* because my SSMS raise an error on N 'FS' /*also in the function you use Invoices:
FROM Invoices
but it must be FROM Invoice
Also please add dates in the table with ANSI format ;-) because we, which are on the other part of the world, have different DATE FORMAT :-)DECLARE @DebtorID int DECLARE @Threshold decimal (14,2) SET @DebtorID = 1 SET @Threshold = 1000.00 SELECT Invoice.InvoiceNum, Invoice.DebtorID, Invoice.InvoiceDate, MAX(Invoice.InvoiceAmount)+ SUM(ISNULL(Inv.InvoiceAmount,0)) AS InvoiceAmount FROM Invoice LEFT JOIN Invoice Inv ON Invoice.DebtorId = Inv.DebtorId AND Invoice.InvoiceDate > Inv.InvoiceDate WHERE Invoice.DebtorID = @DebtorID GROUP BY Invoice.InvoiceNum, Invoice.DebtorID, Invoice.InvoiceDate HAVING MAX(Invoice.InvoiceAmount)+ SUM(ISNULL(Inv.InvoiceAmount,0)) >= @ThresholdTHIS EXAMPLE IS NOT TESTED very well, only against the example data you provided.