TOP N problem with GROUP BY clause

谁都会走 提交于 2019-12-12 19:24:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/757763/top-n-problem-with-group-by-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!