2016-06-14 98 views
0

问题:找出由制造商A.
结果集生产PC和笔记本电脑的平均价格:一个整体均价的所有项目。获得平均错在SQL查询中

Database Schema: 
Product(maker, model, type) 
PC(code, model, speed, ram, hd, cd, price) 
Laptop(code, model, speed, ram, hd, screen, price) 
Printer(code, model, color, type, price) 

我有以下代码:

with totalproducts 
as 
(select price 
from pc 
where model in (
    select model 
    from product 
    where maker='A' 
) 
union 
select price 
from laptop 
where model in (
    select model 
    from product 
    where maker='A' 
)) 
select avg(price) from totalproducts 

不过,我得到的794.4444和解决方案的平均值为754.1666

http://www.sql-ex.ru/learn_exercises.php练习26

任何帮助将高度赞赏

回答

2

可能有更好的解决办法,但解决您的查询的问题:使用union没有all预选赛

删除重复的,想必有可能是一台PC和与同价位的笔记本电脑。将其更改为union all以保留两组中的重复项,并且您可能会得到预期的结果。

+0

就是这样。非常感谢 – Sam

1

只要是明确的,一个简单的版本是这样的:

select avg(price) 
from pc 
where model in (select model 
       from product 
       where maker='A');