declare @tbl table(vndnbr int, InvNbr int, InvAmt numeric(18,6),ChkNbr int)insert into @tblSELECT 687840 , 423099 , -23.000000,1 union allSELECT 687840 , 423099 , -23.000000,2 union allSELECT 687840 , 423099 , 23.000000,3 union allSELECT 603031 , 106541 , -781.410000,1 union allSELECT 603031 , 106541 , -781.410000,1 union allSELECT 603031 , 106541 , 781.410000,1Select *FROM (Select S1.*, S2.Cnt , rn = ROW_NUMBER() OVER (PARTITION BY InvAmt_Sum ORDER BY ChkNbr DESC)From @tbl as S1Inner join ( Select VndNbr, InvNbr, Sum(InvAmt) as InvAmt_Sum, Count(*) as CntFrom @tblGroup By VndNbr, InvNbr) as S2ON S1.InvNbr = S2.InvNbrAND S1.VndNbr = S2.VndNbrAND S1.InvAmt = S2.InvAmt_SumWhere S2.Cnt > 2AND InvAmt_Sum < 0) NegQryWhere rn = 1