简体   繁体   中英

In SQL, how do I select * from a table, but when multiple rows have the same field, select only the ones where another field B is MAX?

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

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM