BrinkDaDrink
BrinkDaDrink

Reputation: 1798

Get max row per group from a related table

This is my first time asking a question on here. It has been very helpful with learning.

I am trying to select a table and getting only rows that have a maximum value for its particular group in another table. One of the best answers that is very close but not quite there is this one (SQL Select only rows with Max Value on a Column) but it only relates to a single table. I have found some others with multiple table but not sure how exactly to use it.

I have a table with (simplified)

prodID, quantity, mach, etc

I then have a table with

prodStatusID, prodID, userID, subStatusID

a last table with sub status names

subStatusID, subStatusName

I am trying to get a table with all of the first table and the second table but only with the row that has the maximum status number and include the right status name.
My other concern which may not matter now but in a year or two when this thing starts to really fill up is performance. I dont know bad it is to have select inside a select but if I am trying to return all productions then it will be doing a query for every production.

Just to be clearer. in the second table prodStatus there might be 2 rows with prodID of 4 but the subStatusID for the first one would be 1 and the second one would be 2. The userID will be different. All I want to get back is the second row because it has the highest status number and I need the userID and statusName associated with that row.

I have been googling for 2 days to get this answer and I saw 1 about auctions but I just dont fully understand it even after researching it.

Upvotes: 1

Views: 896

Answers (1)

John Woo
John Woo

Reputation: 263843

You need to create a subquery which get the maximum value of subStatusID for each prodID.

SELECT  a.*,     -- select only columns that you want to show
        c.*,     -- asterisks means all columns
        d.*
FROM    table1 a
        INNER JOIN
        (
            SELECT prodID, max(subStatusID) maxID
            FROM table2
            GROUP BY prodID
        ) b ON a.prodID = b.prodID 
        INNER JOIN  table2 c
            ON b.prodID = c.prodID AND
                b.maxID = c.subStatusID
        INNER JOIN table3 d
            ON c.subStatusID = d.subStatusID

Upvotes: 1

Related Questions