计算表中的出现次数然后用于查找平均值

时间:2012-09-02 14:00:46

标签: mysql sql

表1

categoryid   categoryname   categorydescription
1               a             zzzzzzz
2               b              yyyyyy
3               c               uuuuu

表2

carid caryear carmodel carprice catid(foreign key to category id )
1        xxxx    aaaa    xxxx    1
2       xxxx     bbbb    xxxx    3
3       xxxx     cccc    xxxx    4
3       xxxx     dddd    xxxx    3
4       xxxxx    eeee    xxxx    1

结果

categoryname                               averageprice                         total cars
a               sum price of same category car / no of same category cars           1
b               sum price of same category car / no of same category cars           2
c               sum price of same category car / no of same category cars           2

1 个答案:

答案 0 :(得分:2)

你可以写:

 SELECT category.categoryname,
        AVG(car.carprice) AS "averageprice",
        COUNT(car.carid) AS "total cars"
   FROM category
   LEFT
  OUTER
   JOIN car
     ON car.catid = category.categoryid
  GROUP
     BY category.categoryname
;

注意:

  • 你没有提到你的桌子的名字,所以我不得不猜测。
  • 这将包括没有任何车辆的类别。如果您只想包含至少有一辆车的类别,请删除LEFT OUTER部分。