分组列的平均值

时间:2016-11-02 03:14:14

标签: postgresql

我的桌子是这样的

id ...... amount...........food
+++++++++++++++++++++++++++++++++++++
1 ........ 5 ............. banana  
1 ........ 4 ............. strawberry  
2 ........ 2 ............. banana  
2 ........ 7 ............. orange  
2 ........ 8 ............. strawberry  
3 ........ 10 .............lime  
3 ........ 12 .............banana  

我想要的是每个食物的表格显示,以及每个食物中出现的平均次数。

我觉得这个表应该是这样的:

    food ........... avg............
    ++++++++++++++++++++++++++++++++
    banana .......... 6.3 ............
    strawberry ...... 6 ............
    orange .......... 7 ............
    lime ............ 10 ............

我不确定如何做到这一点。如果我只使用avg(金额),那么它只会添加全量列

1 个答案:

答案 0 :(得分:2)

你试过GROUP BY吗?

SELECT food, AVG(amount) "avg"
  FROM table1
 GROUP BY food

这是SQLFiddle

输出:

|       food |               avg |
|------------|-------------------|
|       lime |                10 |
|     orange |                 7 |
| strawberry |                 6 |
|     banana | 6.333333333333333 |