Results 1 to 4 of 4

Thread: Grouping question

  1. #1
    Join Date
    Nov 2006
    Posts
    2

    Grouping question

    A simple query I can’t get my brain around:

    I have a table that looks like this:

    Col1 Col2 Col3
    1 a 1
    1 b 2
    1 c 3

    Assume there are many more rows with different values for all columns. I want to return Col1 and Col2 based on the max value of Col3 grouped by Col1. I don’t want to aggregate Col2 but just want the value that corresponds to the aggregate max of Col3.

    “SELECT Col1, Col2, MAX(Col3) GROUP BY Col1, Col2” doesn’t give me what I want and “SELECT Col1, Col2, MAX(Col3) GROUP BY Col1” isn’t allowed because Col2 isn’t aggregated or listed in the GROUP BY clause. How do I get the values of Col1 and Col2 based on the max of Col3 for the group of Col1?

  2. #2
    Join Date
    Nov 2006
    Posts
    7

    Post

    Hi JDTWorld,

    Not sure if it is the most effective solution, but the below code should work given the example you gave.

    Code:
    SELECT 
    	parent.col1, 
    	parent.col2, 
    	MAX(parent.col3) 
    FROM 
    	<your_table> AS parent
    WHERE 
    	parent.col3 = (SELECT MAX(child.col3) 
    			from <your_table> AS child 
    			where child.col1 = parent.col1)
    GROUP BY 
    	parent.col1, 
    	parent.col2
    Faris

  3. #3
    Join Date
    Nov 2006
    Posts
    2
    Works like a champ. Thanks for your insight.

  4. #4
    Join Date
    Nov 2006
    Posts
    7
    No worries, glad I could help.

    Faris

Posting Permissions

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