0

表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
4

1 に答える 1

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
;

ノート:

  • テーブルの名前について言及していないので、推測する必要がありました。
  • これには、車がないカテゴリが含まれます。少なくとも 1 台の車を含むカテゴリのみを含めたい場合は、LEFT OUTERパーツをドロップします。
于 2012-09-02T14:06:44.483 に答える