tags:

views:

161

answers:

2

This is a very easy query (I think) but I stil can't do it.

I have some data like this:

A          B        C
1        1100       5  
1        1100       5
1         500       1
2        1200       4
2        1200       4
2         600       1
3        1300       3
3        1300       3
3         700       1

And I want to return the top B per A with the SUM of C, or something like this:

A     B    C
1   1100   10
2   1200   8
3   1300   6

Also, I'm using DB2 for AS400, so I can't use the TOP keyword.

EDIT @ OMG Ponies:

I tried somethine like

SELECT
   t.A
   ,MAX(t.B)
   ,SUM(t.C)
FROM t
GROUP BY
   t.A

But it returns the total sum of C, not only the ones selected:

A    B    C
1   1100  11
2   1200  9
3   1300  7

Thanks!

+3  A: 

Looks like you want the max B value for each A value, so

  SELECT t.a,
         MAX(t.b)
    FROM TABLE t
GROUP BY t.a

If you want entire record associated with the A and MAX(b) values, use:

SELECT t.a,
       t.b,
       t.c
  FROM TABLE t
  JOIN (SELECT x.a,
               MAX(x.b) AS max_b
          FROM TABLE x
      GROUP BY x.a) y ON y.a = t.a
                     AND y.max_b = t.b
OMG Ponies
Thanks, your solution worked, however, I though with this I could get something else to work, but it didn't. Can you give me a hand with this too? Read question edit please. Thanks =).
Carlo
@Carlo: Updated, not sure if that is what you're after.
OMG Ponies
Works like a charm. It needed GROUP BY t.A, t.B at the end though.Thanks!! Great answer.
Carlo
+1  A: 

On DB2 you can use the FETCH FIRST # ROWS ONLY to mimic the TOP predicate but it goes at the END of the SQL statement

Leslie