tags:

views:

40

answers:

2
+2  Q: 

SQL partial max

Struggling with the following SQL problem.

Assume a three dimensional table with entries (h,t,q)

  1,A,20
  1,A,10
  1,B,5
  2,A,10
  2,B,3
  2,B,8
  3,C,50
  4,A,10
  etc.

I would like to extract

 1,30
 2,11
 3,50
 etc.

group by the first element and then return the maximum q value of the same type, i.e. for header number 2 there are 10 As and 11 Bs, so return 11.

The "max" element (A in case 1, B in case 2 and C in case 3) is irrelevant. I just need to get out the header and that maximum value.

This shouldn't be too tricky, but I can't get it to work. Using MS Access, but can use SQL within.

A: 

Something like this should work:

select h, max(q) from table
group by h

Edit: Never mind.. I misunderstood. Quassnoi's solution should work.

Nelson
+2  A: 
SELECT  h, MAX(cnt)
FROM    (
        SELECT  h, SUM(q) AS cnt
        FROM    mytable
        GROUP BY
                h, t
        ) sq
GROUP BY
        h
Quassnoi
Thanks, exactly what I want. Have to admit that I didnt know that you can group by multiple fields in one call.
Rob