Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Poor performing query with a sebquery in the select 1

Status
Not open for further replies.

smn198

Technical User
Oct 29, 2004
24
0
0
GB
Hi all,

I'm trying to improve the performance of a very slow running query. I'm linking master records to child or payment records via an intermediate table. Diagram:
For each master record there may be many entries (or 0) in the linking table and for each entry in the linking table there will be one child or payment record.

To get the most recent child or payment record for each master record I am using the following SQL. Can anyone thing of a more efficient way of doing this?

Code:
select
  rga.RecurringGiftID,
  (
    select top 1
      p.RESystemId
    from
      dbo.WH_Gift p
    where
      p.RESystemID = rga.PaymentId
    order by
      p.date desc) LastPaymentID
from
  RGA_Activity rga

TIA
 
You may try this:
SELECT rga.RecurringGiftID, p.LastPaymentID
FROM RGA_Activity rga INNER JOIN (
SELECT RESystemID, MAX(PaymentId) LastPaymentID FROM dbo.WH_Gift GROUP BY RESystemID
) p ON rga.PaymentId = p.RESystemID

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
I didn't explicitly state it be a greater payment id doesn't nessisarily mean that it is a later gift (which is what I'm after).

RGA_Activity rga table
RecurringGiftID field
PaymentID field (fk to WH_Gift.RESystemID)

WH_Gift p table
RESystemID field
Date field

For each
RGA_Activity.RecurringGiftID I want the most recent WH_Gift.RESystemID

Thanks,
Steve
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top