[英]How do I select rows in table (A) sharing the same foreign key (itemId) where multiple rows in table have the values in table B
[英]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?
例如,我有一个表
ID | 汽车零件编号 | 汽车零件价格 | 元数据 |
---|---|---|---|
1 | 扳手 | 580 | 其他一些数据 |
2 | 扳手 | 570 | 其他数据 2 |
3 | 车轮 | 423 | 其他一些数据 |
4 | 窗户 | 234 | 其他一些数据 |
5 | 引擎 | 568 | 其他数据 1 |
6 | 引擎 | 423 | 其他数据 2 |
请注意,当我执行 SELCT * FROM 这个表时,我会得到两行 CarPartId,但我真正想要的是获取 CarPartId 行,其中 CarPartPrice 是最高的,以及表中的其他行。
我如何实现这一目标? 例如,我的查询应该返回这个
ID | 汽车零件编号 | 汽车零件价格 | 元数据 |
---|---|---|---|
1 | 扳手 | 580 | 其他一些数据 |
3 | 车轮 | 423 | 其他一些数据 |
4 | 窗户 | 234 | 其他一些数据 |
5 | 引擎 | 568 | 其他数据 1 |
由于您说“连同表中的其他行”,我知道您想查看所有行。 所以下面将显示所有数据,但在顶行以最高的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.