Friday, April 29, 2011

TOP N problem with GROUP BY clause

The problem: I need to find all active [GiftPledges] that have the last three [GiftDetails] have a zero amount.

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) >= 3

Now, I have all my [GiftPledges] that have at least three [GiftDetails].

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

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.

I found this article about "Top n per Group" and that seems like the direction I need to be headed, but I'm not sure I'm on the right track.

Any help, clarifications or suggestions would be greatly appreciated.

From stackoverflow
  • 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) >= 3 
    AND
    GP.PledgeID in (
    SELECT PledgeID From
    (
    SELECT TOP 3 gp.PledgeID, gdi.Amt  FROM GiftDetail gdi
          INNER JOIN GiftHeader ghi ON gdi.GiftRef = ghi.GiftRef
          WHERE gdi.PledgeId = gp.PledgeId
          ORDER BY ghi.GDate DESC
    ) x_amt 
    Group By PledgeID
    Having SUM(AMT) ) x_sum = 0
    

    something like that anyway.

0 comments:

Post a Comment