Link to home
Start Free TrialLog in
Avatar of frimy
frimyFlag for United States of America

asked on

Select only the maximum amount for each customer from a list MS 2010

I have list from all customers the daily open balance by date (I'm getting it from the Running Sum total).
I need to get only the largest Open Balance for any date for each customer.

I'm using created the following query.
It only works with little records.
But with a lot records I get an error "At most one record can be returned by this subquery"
Thanks in advance

MaxAmt: (SELECT top 1 [RunningSum ] FROM [qCustBal AddRunAmt] WHERE CustomerID=[Customer].[CustomerID] ORDER BY RunningSum Desc)
Avatar of Hamed Nasr
Hamed Nasr
Flag of Oman image

Try this for tbl (CustID, fld) to get maximum value of fld for each CustID.

SELECT a.CustID, (SELECT MAX(b.fld)  FROM tbl AS b WHERE b.CustID = a.CustID)
FROM tbl AS a
GROUP BY a.CustID

Open in new window

Provide some sample data and expected result.
Avatar of frimy

ASKER

Hamed,

it works very good.
but it's running very slow.

I have 5,630 records (test only)
to add a running total it takes about 3 seconds (from Dale)
But to the get the maximum value for each customer (the greatest amount), it takes about 9 minutes to run.
Is it possible to make it faster?
Thanks
ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you have other needs, the ordinary Group By query can be part of the FROM clause of another (higher level) query, joined on the custid field.
I go with aikimark's comment, for this question.
Avatar of frimy

ASKER

aikimark, it works beautiful, it's funny I didn't think of it because I use it all the time.
maybe because I was focusing on the Add Running total query.
thanks