title: TOP N problem with GROUP BY clause
body: <p>The problem: I need to find all active [GiftPledges] that have the last three [GiftDetails] have a zero amount.</p>
  
  <pre><code>SELECT gp.PledgeId FROM GiftPledge gp
        INNER JOIN GiftDetail gd ON gp.PledgeId = gd.PledgeId
        WHERE gp.PledgeStatus = 'A'
        GROUP BY PledgeId
        HAVING COUNT(PledgeId) &gt;= 3
  </code></pre>
  
  <p>Now, I have all my [GiftPledges] that have at least three [GiftDetails].</p>
  
  <pre><code>SELECT TOP 3 gdi.Amt FROM GiftDetail gdi
        INNER JOIN GiftHeader ghi ON gdi.GiftRef = ghi.GiftRef
        WHERE gdi.PledgeId = gp.PledgeId
        ORDER BY ghi.GDate DESC
  </code></pre>
  
  <p>This gives me the three most recent [GiftDetails] associated with a given [GiftPledge].  The problem is that I don't know how to sum the second query and have it be a part of the WHERE clause in the first query.</p>
  
  <p>I found <a href="http://weblogs.sqlteam.com/jeffs/archive/2007/03/30/More-SQL-Server-2005-Solutions.aspx" rel="nofollow noreferrer">this article</a> about "Top n per Group" and that <em>seems</em> like the direction I need to be headed, but I'm not sure I'm on the right track.</p>
  
  <p>Any help, clarifications or suggestions would be greatly appreciated.</p>