>select a.TipID, a.AMOUNT*1000 as OldProgram, a.FundType, a.Year, isnull(sum(b.amount),0) as AmountSpent, isnull(c.AMOUNT*1000,0) as NewProgram >from TIP_ApprovedFunding a >left join TIP_Ledger b on a.tipid = b.tipid and a.fundtype=b.fundtype and a.year = b.fisyear >left join TIP_ProposedFunding c on a.tipid = c.tipid and a.fundtype=c.fundtype and a.year = c.year >where a.YEAR= 2013 >group by a.TipID, a.amount, a.FundType, a.YEAR, c.amount >order by a.TipID >>I need to take it one step further and filter the result to only the records where AmountSpent is > NewProgram. My attempts to do this have all failed. Apparently there needs to be a subquery or HAVING clause involved which I don't understand. Can someone help please?
;with cte as (select a.TipID, a.AMOUNT*1000 as OldProgram, a.FundType, a.Year, isnull(sum(b.amount),0) as AmountSpent, isnull(c.AMOUNT*1000,0) as NewProgram from TIP_ApprovedFunding a left join TIP_Ledger b on a.tipid = b.tipid and a.fundtype=b.fundtype and a.year = b.fisyear left join TIP_ProposedFunding c on a.tipid = c.tipid and a.fundtype=c.fundtype and a.year = c.year where a.YEAR= 2013 group by a.TipID, a.amount, a.FundType, a.YEAR, c.amount) SELECT * FROM cte WHERE AmountSpent > NewProgram order by TipIDOr alternatively:
select a.TipID, a.AMOUNT*1000 as OldProgram, a.FundType, a.Year, isnull(sum(b.amount),0) as AmountSpent, isnull(c.AMOUNT*1000,0) as NewProgram from TIP_ApprovedFunding a left join TIP_Ledger b on a.tipid = b.tipid and a.fundtype=b.fundtype and a.year = b.fisyear left join TIP_ProposedFunding c on a.tipid = c.tipid and a.fundtype=c.fundtype and a.year = c.year where a.YEAR= 2013 group by a.TipID, a.amount, a.FundType, a.YEAR, c.amount HAVING isnull(sum(b.amount),0) > isnull(c.AMOUNT*1000,0) order by a.TipID