oracle SQL PLUS-显示表

cnh2zyt3  于 2023-05-16  发布在  Oracle
关注(0)|答案(2)|浏览(107)

我需要编写一个查询,以显示产品平均价格最高的品牌的品牌ID、品牌名称、品牌类型和产品平均价格
我可以通过输入获得所有品牌的平均价格:

SQL> SELECT LGPRODUCT.BRAND_ID, BRAND_NAME, BRAND_TYPE,    ROUND(AVG(PROD_PRICE),2)
FROM BOFF.LGPRODUCT, BOFF.LGBRAND
WHERE LGPRODUCT.BRAND_ID = LGBRAND.BRAND_ID
GROUP BY LGPRODUCT.BRAND_ID, BRAND_NAME, BRAND_TYPE
ORDER BY LGPRODUCT.BRAND_ID;

但是如果我输入ROUND(MAX(AVG(PROD_PRICE)),2)我得到一个错误,有什么建议吗?

z9ju0rcb

z9ju0rcb1#

您可以使用窗口函数rank根据平均值标记排名,然后过滤以获得排名最高的行:

select *
from (
    select lgproduct.brand_id,
        brand_name,
        brand_type,
        round(avg(prod_price), 2),
        rank() over (
            order by round(avg(prod_price), 2) desc
            ) as rnk
    from boff.lgproduct,
        boff.lgbrand
    where lgproduct.brand_id = lgbrand.brand_id
    group by lgproduct.brand_id,
        brand_name,
        brand_type
    ) t
where rnk = 1
order by brand_id;

如果您必须使用having,请尝试:

select lgproduct.brand_id,
    brand_name,
    brand_type,
    round(avg(prod_price), 2)
from boff.lgproduct,
    boff.lgbrand
where lgproduct.brand_id = lgbrand.brand_id
group by lgproduct.brand_id,
    brand_name,
    brand_type
having round(avg(prod_price), 2) = (
        select max(round(avg(prod_price), 2))
        from boff.lgproduct,
            boff.lgbrand
        where lgproduct.brand_id = lgbrand.brand_id
        group by lgproduct.brand_id,
            brand_name,
            brand_type
        )
order by lgproduct.brand_id;
9ceoxa92

9ceoxa922#

您会得到错误,因为您不能在SQL中嵌套聚合函数。
使用此命令获取带有max_avg_prod_price的品牌,而不是:

select  bb.brand_ID,    bb.brand_name,  bb.brand_type,  round((avg(pp.prod_price)),2)   as  MaxPrice
                from    BOFF.lgbrand    bb, BOFF.lgproduct  pp
                where   pp.brand_ID =   bb.brand_ID
                group   by  brand_ID
                order by MaxPrice desc
                limit 1;

相关问题