Just a practice problem, little bit confusing I'd appreciate it if somebody could clear this up..

I have a DB called Product and another one called PC. I'm trying to execute a query to "find the average hard disk size of a PC for all those manufacturers who also make printers"

Here's my code:

SELECT maker, AVG(hd) 
FROM pc, product
WHERE pc.model=product.model
GROUP BY maker
HAVING COUNT(type='PR')>=1

type is an attribute of Product which either stands for printer(PR) laptop or PC, however the HAVING statement doesn't seem to single out only the makers who produce printers, instead I get back an AVG for each maker in the Product table.

UPDATE

This is what the relations look like:

Product(maker, model, type)
PC(model, hd, speed, ram, price)
Printer(model, color, type, price)
有帮助吗?

解决方案

Try the following query:

SELECT maker, AVG(hd) FROM PC, Product
WHERE PC.model=Product.model
AND Product.maker IN 
   (SELECT DISTINCT maker FROM Product WHERE type='PR')
GROUP BY Product.maker;

Demo: http://sqlfiddle.com/#!2/abfaa/2

You simply add a condition to make sure that the maker is one of the makers that have at least one printer product. You then group by the maker to find the individual averages.

其他提示

All those manufacturers who make printers:

  SELECT maker
    FROM product
   WHERE type = 'PR'
GROUP BY maker;

Average hard disk size of a PC for all those manufacturers who also make printers

  SELECT p.maker, AVG(pc.hd) avg_hd_size
    FROM
       (
  SELECT maker
    FROM product
   WHERE type = 'PR'
GROUP BY maker
       ) g
    JOIN product p on p.maker = g.maker
    JOIN pc on pc.model = p.model
GROUP BY p.maker;

SELECT maker, avg(hd)

FROM PC INNER JOIN Product

ON PC.model=Product.model

GROUP BY maker

HAVING maker IN (SELECT DISTINCT maker FROM Product WHERE type='Printer')

select distinct maker
      ,avg(hd) as Avg_hd
  from Product
 inner join PC on (Product.model = PC.model)
 where type = 'Pc'
   and maker in (Select maker from Product where type = 'Printer')
 Group by maker
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top