Liroy
Liroy

Reputation: 25

Get MAX value of each record in group by query

I have a query in SQL looks like that:

 select fldCustomer, fldTerminal, COUNT(fldbill)
 from tblDataBills
 group by fldCustomer, fldTerminal
 order by fldCustomer 

results looks like:

 fldCustomer    fldTerminal (number of bills)
 0  1   19086
 0  2   10
 0  5   236
 1  1   472
 1  5   3
 1  500 19
 2  1   292
 2  500 22

how can i get the MAX count of each customer so i get results like

 0 1 19086
 1 1 472
 2 1 292

Thanks in advance!

Upvotes: 2

Views: 62

Answers (2)

Adel Helal
Adel Helal

Reputation: 670

This might require a little trickery with the RANK() function


SELECT fldCustomer, fldTerminal, [(number of bills)]
FROM (
    SELECT fldCustomer, fldTerminal, COUNT(fldbill) [(number of bills)],
        RANK() OVER (PARTITION BY fldCustomer ORDER BY COUNT(fldbill) DESC) Ranking
    FROM tblDataBills
    GROUP BY fldCustomer, fldTerminal
) a
WHERE Ranking = 1

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269483

Use a subquery with row_number():

select fldCustomer, fldTerminal, cnt
from (select fldCustomer, fldTerminal, COUNT(*) as cnt,
             row_number() over (partition by fldCustomer order by count(*) desc) as seqnum
      from tblDataBills
      group by fldCustomer, fldTerminal
     ) db
where seqnum = 1
order by fldCustomer ;

Note that in the event of ties, this will arbitrarily return one of the rows. If you want all of them, then use rank() or dense_rank().

Upvotes: 2

Related Questions