Postgres在AVERAGE函数上使用ORDER BY

时间:2014-01-26 15:54:22

标签: sql-order-by psql

我是Postgres的新手,我正在尝试连接表,获取平均值并按平均值排序。下面描述了两个表:

Table "public.movies"
   Column    |  Type   | Modifiers | Storage  | Stats target | Description 
-------------+---------+-----------+----------+--------------+-------------
 movieid     | integer | not null  | plain    |              | 
 title       | text    |           | extended |              | 
 releasedate | date    |           | plain    |              | 
 url         | text    |           | extended |              | 
 unknown     | integer |           | plain    |              | 
 action      | integer |           | plain    |              | 
 adventure   | integer |           | plain    |              | 
 animation   | integer |           | plain    |              | 
 children    | integer |           | plain    |              | 
 comedy      | integer |           | plain    |              | 
 crime       | integer |           | plain    |              | 
 documentary | integer |           | plain    |              | 
 drama       | integer |           | plain    |              | 



Table "public.ratings"
 Column  |  Type   | Modifiers | Storage | Stats target | Description 
---------+---------+-----------+---------+--------------+-------------
 userid  | integer | not null  | plain   |              | 
 movieid | integer | not null  | plain   |              | 
 rating  | integer |           | plain   |              | 
 time    | integer |           | plain   |              | 
Indexes:
    "ratings_pkey" PRIMARY KEY, btree (userid, movieid)
Foreign-key constraints:
    "ratings_movieid_fkey" FOREIGN KEY (movieid) REFERENCES movies(movieid)
Has OIDs: no

我必须按平均评分排序,因为一个movieid有来自不同用户的多个评级,但我必须按(asc)排序平均评分。我的查询如下,没有ORDER BY的情况下工作正常:

 SELECT (movies.title, AVG(ratings.rating)) 
 FROM movies 
    FULL JOIN ratings ON movies.movieid = ratings.movieid 
 WHERE (movies.comedy = 1) GROUP BY movies.title LIMIT 10;

如果我使用:ORDER BY AVG(ratings.rating)

,它会为所有电影评级返回1.00000000000

任何帮助都将非常感谢!在此先感谢:)

1 个答案:

答案 0 :(得分:3)

要按聚合顺序,您需要使用子查询,或者使用顺序位置作为订单说明符。

以下我有:

  • 将您的FULL JOIN更改为LEFT OUTER JOIN - 如果没有movieid,则评分存在没有意义,如果有,则无效它会在此查询中显示为movieid null的平均评分。

  • 添加ORDER BY 2告诉Pg按平均列排序

导致:

 SELECT movies.title, AVG(ratings.rating)
 FROM movies 
 LEFT OUTER JOIN ratings ON movies.movieid = ratings.movieid 
 WHERE (movies.comedy = 1)
 GROUP BY movies.title
 ORDER BY 2
 LIMIT 10