2016-06-14 117 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');