1

I have a table that looks like this(this is just some of the records and their are also more columns too but these are the ones I care about):

nbr    amt     date     
1      10      10/30/2012
1      15      1/30/2012
1      50      11/30/2012
2      10      4/30/2012
2      1000    5/30/2012
2      45      1/15/2012
4      90      12/30/2012
4      89      8/30/2012
3      100     7/30/2012

I'm trying to select the nbr,amt, and date that corresponds to the max(amt) for each nbr using SQL Server 2012.

I have query like this so far which groups it by nbr and selects the max(amt) but it won't let me select date because its not in an aggregate function but if I put it in an aggregate function it selects max(date) which doesn't corrsepond to the actual date that goes with the amt:

,topamt as (
select 
                 nbr
    ,amt
    ,date
,amtrank = row_number() over (partition by ah.member_nbr order by ah.tran_amt desc)

from HISTORY ah 
      amt>=10
and id=6061
and date between '11-01-2012' and '12-31-2012'

so if I change the query to this where am I defining it to grab the max(amt) the results aren't showing the max atleast.

2
  • If you have the same max amt that occurred on two different days, would you want the first time you hit that amount or the most recent time that hit that amount? Jan 8, 2013 at 20:24
  • doesn't matter whichever is easier to implement
    – Jt2ouan
    Jan 8, 2013 at 20:25

1 Answer 1

4

Try using a ranking function:

with TopAmt as
(
  select *
  , amtRank = row_number() over (partition by nbr order by amt desc)
)
select nbr
  , amt
  , date
from TopAmt
where amtRank = 1
7
  • 1
    +1, this will always retrieve one record. If there is more than one record with the same max amt per nbr, then op can use RANK instead of ROW_NUMBER
    – Lamak
    Jan 8, 2013 at 19:59
  • I don't know if this is the issue but the table I'm looking at has more than 3 columns, those are just the ones i care about. I get the error:nbr was specified multiple times for topamt
    – Jt2ouan
    Jan 8, 2013 at 20:07
  • @Lamak makes a good point; you can include date in the over clause if you're worried about a tie breaker, e.g. (partition by nbr order by amt desc, date) will return the first occurrence of the max amt. Jan 8, 2013 at 20:10
  • yes I've row_number() over(partition... before and yes it retrives one record but it's not select the max.
    – Jt2ouan
    Jan 8, 2013 at 20:16
  • please take a look at question/query above I edited for what I think u suggested
    – Jt2ouan
    Jan 8, 2013 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.