Home > other >  In SQL, how do I select * from a table, but when multiple rows have the same field, select only the
In SQL, how do I select * from a table, but when multiple rows have the same field, select only the

Time:11-11

For example, I have a Table

Id CarPartId CarPartPrice Metadata
1 spanner 580 Some other data
2 spanner 570 Some other data 2
3 wheel 423 Some other data
4 window 234 Some other data
5 engine 568 Some other data 1
6 engine 423 Some other data 2

Notice that when I do a SELCT * FROM this table, I would get two rows of CarPartId, but what I really want is to get the CarPartId row whereby the CarPartPrice is the highest, along with other rows from the table.

How do I achieve this? For example, my query should return this

Id CarPartId CarPartPrice Metadata
1 spanner 580 Some other data
3 wheel 423 Some other data
4 window 234 Some other data
5 engine 568 Some other data 1

CodePudding user response:

try this:

SELECT * from table INNER JOIN
  (SELECT CarPartId, MAX(CarPartPrice) as MaxPrice
    FROM table GROUP BY CarPartId
  ) grouptable
ON table.CarPartId = grouptable.CarPartId
AND table.CarPartPrice = grouptable.MaxPrice

CodePudding user response:

Since you say "along with other rows from the table" I understand you want to see all the rows. So below will show all data but sorted with highest CarPartPrice at the top row:

Select * From this table
Order by CarPartPrice

CodePudding user response:

I'd use a nested query.

SELECT t1.*
  FROM Table t1
 WHERE t1.CarPartPrice = ( SELECT MAX(t2.CarPartPrice)
                             FROM Table t2
                         GROUP BY t2.CarPartId
                           HAVING t2.CarPartId = t1.CarPartId)

The nested query will give you the highest CarPartPrice per Id.

CodePudding user response:

I think what you are looking for is select max()

SELECT CarPartId, MAX(CarPartPrice)
FROM this table 
GROUP BY CarPartId
  • Related