0

我有 4 张桌子。我试图为每个汽车品牌获得最大价值。有10个品牌。我试图找出每个品牌最贵的车。

我做的第一件事是将所有我想从中获取信息的表格分组。我已经加入了 BRAND、MODEL、CLASS 和 VEH 表。但是,我不确定如何获得每个组的最大值。

SELECT B.BRAND_NAME, M.MODEL_NAME, C.CLASS_NAME, V.VEH_YEAR,  V.VEH_PRICE

FROM ((VEHICLE V INNER JOIN CLASS C ON V.CLASS_ID = C.CLASS_ID)
INNER JOIN MODEL M ON M.MODEL_ID = V.MODEL_ID)
INNER JOIN BRAND B ON B.BRAND_ID = M.BRAND_ID

在此处输入图像描述

我试过:

SELECT B.BRAND_NAME, M.MODEL_NAME, C.CLASS_NAME, V.VEH_YEAR,  V.VEH_PRICE
FROM (
SELECT B.BRAND_NAME, MAX(V.VEH_PRICE)
FROM ((VEHICLE V INNER JOIN CLASS C ON V.CLASS_ID = C.CLASS_ID)
INNER JOIN MODEL M ON M.MODEL_ID = V.MODEL_ID)
INNER JOIN BRAND B ON B.BRAND_ID = M.BRAND_ID
GROUP BY B.BRAND_NAME
);

我越来越:在此处输入图像描述

4

1 回答 1

1

如果您只想要每个品牌的最高车辆价格,您的加入会很好。它只需要一个GROUP BYMAX()函数(注意你不需要这个Class表):

SELECT B.BRAND_NAME, 
       MAX(V.VEH_PRICE) AS MAX_VEH_PRICE

FROM ( VEHICLE V
  INNER JOIN MODEL M ON M.MODEL_ID = V.MODEL_ID )
  INNER JOIN BRAND B ON B.BRAND_ID = M.BRAND_ID

GROUP BY B.BRAND_ID, B.BRAND_NAME ;

要获取具有最高价格的车辆的所有车辆数据,您需要在子查询(派生表)中编写上一个查询,然后再次连接:

SELECT B.BRAND_NAME, M.MODEL_NAME, C.CLASS_NAME, V.VEH_YEAR,  V.VEH_PRICE

FROM  
    ( ((VEHICLE V INNER JOIN CLASS C ON V.CLASS_ID = C.CLASS_ID)
      INNER JOIN MODEL M ON M.MODEL_ID = V.MODEL_ID)
      INNER JOIN BRAND B ON B.BRAND_ID = M.BRAND_ID
    )

  INNER JOIN

    ( SELECT M.BRAND_ID, 
             MAX(V.VEH_PRICE) AS VEH_PRICE  
      FROM (VEHICLE V
        INNER JOIN MODEL M ON M.MODEL_ID = V.MODEL_ID)
      GROUP BY M.BRAND_ID 
    ) AS derived

    ON  b.BRAND_ID = derived.BRAND_ID
    AND v.VEH_PRICE = derived.VEH_PRICE ;
于 2012-11-25T20:27:00.910 回答