0

我有一个包含表格的数据库:车辆(一辆蓝色本田思域,售价 3 万美元)、品牌(本田)和模型(思域)。

我正在尝试创建一个相关的子查询,它将为我提供每个品牌中价格最高的汽车的 VEH_ID。

简单地说,我想知道所有品牌的汽车成本最高。

我已经附上了一张图片,我正在尝试使用 SQL,但它不起作用。很可能是因为我不知道我在做什么。 在此处输入图像描述

SELECT 
BRAND.BRAND_ID, BRAND_NAME, VEHICLE.MODEL_ID, VEH_ID
FROM BRAND, MODEL, VEHICLE
WHERE VEH_PRICE = 
( 
SELECT MAX(VEH_PRICE)
FROM VEHICLE
)
GROUP BY BRAND.BRAND_ID, BRAND_NAME, VEHICLE.MODEL_ID, VEH_ID;
4

1 回答 1

1

create a new query on the vehicles table grouping by brandID to determine the max(price)

SELECT brandID, MAX(VEH_PRICE)
FROM VEHICLE
group by brandID

then create another query that uses the first one joined back to vehicles to determine the related vehicleID

SELECT 
v.BRAND_ID, MODEL_ID, VEH_ID

FROM VEHICLE v inner join
(    SELECT brandID, MAX(VEH_PRICE) as max_veh_price
    FROM VEHICLE
    group by brandID) m on
v.brandid = m.brandid and
v.veh_price = m.max_veh_price

then, to get the brand_name, join again to your brand table on the brandID field, and yes, if max(price) returns more than one vehicle, you'll have to go with Top 1 at Roman suggests.

sorry, couldn't read your images at first.

yes, you need to join the model table to vehicle to get to the brandID. I'm assuming this is an exercise and you're supposed to learn about joins as a result? don't just take a solution, then, understand each piece individually.

于 2012-11-21T19:37:15.697 回答