Results 1 to 2 of 2
  1. #1
    Join Date
    Jul 2006
    Posts
    111

    Unanswered: group by, max and another column

    Hi,

    Say I have the table below:

    Tabl1

    PKey ColA ColB ColC
    1 a1 b1 c1
    2 a1 b2 c2
    3 a1 b3 c3
    ... a2 ...
    ...
    ... a3 ...
    ...

    If I group by ColA with the select statement as follows:

    Code:
    SELECT
         ColA, MAX(ColB), 
    FROM
         Tabl1
    GROUP BY
          ColA
    If for example for a1 the MAX(ColB) is b2, THEN I would like to include ColC in the select statement such that for a1 the resulting row would be:

    ColA ColB ColC
    a1 b2 c2

    What is the best way to do this?
    TIA!

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    the best way? only the optimizer has the final word

    here is one way: take the query you posted, which finds the max ColB for each ColA, and join it back to the table as a subquery

    Code:
    SELECT
      FROM Tabl1
    INNER
      JOIN (  your query here )
        ON ...
    note that you need to join on not only the ColAs, but also ColB to the max value of ColB
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •