每个组的MAX for SQL

时间:2012-11-25 19:59:06

标签: sql ms-access group-by max correlated-subquery

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

我做的第一件事是将我想要获取信息的所有表格分组。 我加入了表品牌,型号,类别和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

enter image description here

我试过了:

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
);

我得到:enter image description here

1 个答案:

答案 0 :(得分: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 ;