SQL - 嵌套聚合

时间:2013-03-06 04:12:09

标签: sql max having average

我有这个:

    SELECT BRAND_ID, CAST (ROUND (AVG(PROD_PRICE), 2) AS NUMERIC (9, 2)) AS 'LARGEST AVERAGE'
    FROM LGPRODUCT
    GROUP BY BRAND_ID

它显示了一堆平均价格,每个品牌,就像它应该的那样。

但是,如果我只想显示最高数字呢?还是最低的?

我一直试图以各种不同的方式使用MAX,并尝试过使用WHERE和HAVING。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

由于您提及RDBMS,因此以下查询适用于大多数rdbms。

SELECT  BRAND_ID, 
        CAST (ROUND (AVG(PROD_PRICE), 2) AS NUMERIC (9, 2)) AS 'LARGEST AVERAGE'
FROM    LGPRODUCT
GROUP   BY BRAND_ID
HAVING  CAST (ROUND (AVG(PROD_PRICE), 2) AS NUMERIC (9, 2)) =
        (
            SELECT  MAX(xx)
            FROM
            (
                SELECT  CAST (ROUND (AVG(PROD_PRICE), 2) AS NUMERIC (9, 2)) as xx
                FROM    LGPRODUCT
                GROUP   BY BRAND_ID
            ) s
        )

上述查询的一个优点是,它处理重复项( BRAND_ID具有最大平均值