我需要在两个单独的表格中找到两种产品的平均价格,其中两种产品的制造商都相同

时间:2019-07-12 17:49:35

标签: sql subquery aggregate

问题:找出制造商A生产的PC和笔记本电脑的平均价格。 结果集:所有商品的整体平均价格。

产品表:

enter image description here

PC表:

enter image description here

打印机表:

enter image description here

笔记本电脑桌:

enter image description here

我的代码:

select (avg(pc.price)+avg(printer.price))/2 from pc, printer
where pc.model IN
(SELECT product.model from PRODUCT where maker='A')
AND
printer.model IN
(SELECT printer.model from product where maker  = 'A')

我的结果和正确的结果: enter image description here

1 个答案:

答案 0 :(得分:1)

我认为要求不是2个平均值的平均值。
您所能做的就是按制造商“ A”选择所有价格的笔记本电脑和所有笔记本电脑,然后找到所有笔记本电脑的平均值。
您将必须使用UNION ALL从两个表pclaptop中选择所有价格:

select avg(t.price) AVG_price from (
  select price from pc
  where model in (select model from product where maker = 'A')
  union all
  select price from laptop
  where model in (select model from product where maker = 'A')
) t

但是,如果是平均值的平均值,则遵循相同的逻辑,计算2个平均值并应用UNION ALL以获得平均值:

select avg(t.price) AVG_price from (
  select avg(price) price from pc
  where model in (select model from product where maker = 'A')
  union all
  select avg(price) price from laptop
  where model in (select model from product where maker = 'A')
) t