写一个查询,以获得所有药物的详细信息,其价格高于同类型所有药物的平均价格

时间:2017-05-01 13:17:02

标签: mysql sql

enter image description here

正如问题所说,我对此代码有错误:

select *, avg(price) as average 
from drug 
having avg(drug.price) > (select count(price) from drug) 

请帮助我。

2 个答案:

答案 0 :(得分:1)

由于我不知道您使用的是哪种数据库,因此我在此处写了通用 -

select a.* 
 from drug a
 where a.price > ( select avg(b.price) from drug b where b.type= a.type)

答案 1 :(得分:0)

我不确定这是否是性能最佳的解决方案,但这就是我接近它的方式:

WITH avg_by_type AS (
SELECT type, avg(prive) as avg_type
FROM drug
GROUP BY type
)
SELECT *
FROM drug 
INNER JOIN avg_by_type ON avg_by_type.type = drug.type AND avg_by_type.price < drug.price