-1

我有这样的记录:

name       price    class
Horse      5000     mammal
Cat        3000     mammal
penguin    2000     bird
chicken    1000     bird
turtle     4000     reptile
snake      2400     reptile

我需要一个包含以下列的表:名称、价格、类、priceavg_of_class 例如:

name       price    class    priceavg_of_class
Horse      5000     mammal   4000
Cat        3000     mammal   4000
penguin    2000     bird     1500
chicken    1000     bird     1500
turtle     4000     reptile  3200
snake      2400     reptile  3200

如何使用 SQL 解决这个问题?

我试过这段代码:

SELECT animal.name, animal.price, animal.class, 
(SELECT Avg(animal.price) FROM animal WHERE class = animal.class) AS Avg
FROM animal

但这似乎不起作用。我为每条记录得到相同的平均值。

4

3 回答 3

3

这是一种通过显式连接执行此操作的方法:

select name, price, class, avgprice
from animal t inner join
     (select class, avg(price) as avgprice
      from animal t
      group by class
     ) tavg
     on t.class = tavg.class

您的查询(这是一种替代解决方案)的问题是变量的范围。如果您包含所有列的别名,那么它将起作用:

SELECT a.name, a.price, a.class, 
       (SELECT Avg(a2.price) FROM animal a2 WHERE a.class = a2.class
       ) AS Avg
FROM animal a

你有class = animal.class。这两个都引用animal内部查询中的表,因为最近的范围是用于解析列引用的范围。

于 2013-03-21T17:19:16.860 回答
1

使用子查询和聚合函数

Select name, price, class, 
    (select Avg(price) From table
     where class = t.class) avgPrice
From table t
于 2013-03-21T17:07:51.657 回答
0
select name,price,class,avg(price) over (partition by class)
from tab;

SELECT m.name,
  m.price,b.class,b.price
  FROM tab m,
  (SELECT class,AVG(price) price FROM tab GROUP BY class
  ) b
  where m.class=b.class
于 2013-03-21T18:32:30.290 回答