[英]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.请注意,当我执行 SELCT * FROM 这个表时,我会得到两行 CarPartId,但我真正想要的是获取 CarPartId 行,其中 CarPartPrice 是最高的,以及表中的其他行。
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:
所以下面将显示所有数据,但在顶行以最高的 CarPartPrice 排序:
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.嵌套查询将为您提供每个 Id 的最高 CarPartPrice。
I think what you are looking for is select max()我认为您正在寻找的是 select max()
SELECT CarPartId, MAX(CarPartPrice)
FROM this table
GROUP BY CarPartId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.