在 SQL 中,我如何 select * 来自 table,但是当多行具有相同的字段时,select 只有另一个字段 B 为 MAX 的行?

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?

比如我有一个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

请注意,当我执行 SELCT * FROM this table 时,我会得到两行 CarPartId,但我真正想要的是得到 CarPartId 行,其中 CarPartPrice 最高,以及其他行来自 table.

的行

我该如何实现?例如,我的查询应该 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

既然您说“以及 table 中的其他行”,我理解您想要查看所有行。所以下面将显示所有数据,但在顶行以最高 CarPartPrice 排序:

Select * From this table
Order by CarPartPrice

试试这个:

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

我会使用嵌套查询。

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

嵌套查询将为您提供每个 ID 的最高 CarPartPrice。

我想你要找的是 select max()

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