0

Question: Find out the average price of PCs and laptops produced by maker A.
Result set: one overall average price for all items.

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)

I have the following code:

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

However, I get an average of 794.4444 and solution is 754.1666

in: http://www.sql-ex.ru/learn_exercises.php Exercise 26

Any help would be highly appreciated

3 Answers 3

3

There might be better solutions, but to address the problem in your query:

Using union without the all qualifier removes duplicates, and presumably there might be a pc and a laptop with the same price. Change it to union all to keep duplicates from both sets and you'll probably get the expected result.

Sign up to request clarification or add additional context in comments.

1 Comment

That was it. Thank you so much
1

Just to be clear, a simpler version looks like this:

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

Comments

-1

Your solution is to use union all:

SELECT AVG(price) AS price
FROM (SELECT price,'pc' AS type
          FROM pc JOIN product ON product.model=pc.model WHERE maker ='a'
      UNION ALL
      SELECT price, 'laptop' AS type
          FROM laptop JOIN product ON product.model=laptop.model WHERE maker ='a')
   AS tow (price,type)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.