使用Avg和Group by

时间:2012-11-11 23:51:00

标签: mysql sql group-by average

我正在编写一个需要根据每种类型计算电影平均成本的查询。 我正在使用MySQL编写此查询。 到目前为止,我有`

SELECT 
    MOVIE_NUM,
    MOVIE_GENRE,    
    ROUND(AVG(MOVIE_COST), 2) AS 'AVERAGE COST',
    MOVIE_COST
FROM
    MOVIE
GROUP BY MOVIE_GENRE 
ORDER BY MOVIE_NUM

这给了我以下输出:

MOVIE_NUM  MOVIE_GENRE  AVERAGE COST  MOVIE_COST
1234       FAMILY       39.95         39.95
1235       ACTION       52.72         59.95
1236       DRAMA        58.46         59.95
1237       COMEDY       44.12         29.95

但是我需要这种格式:

MOVIE_NUM  MOVIE_GENRE  AVERAGE COST  MOVIE_COST
1234       FAMILY       39.95         39.95
1235       ACTION       52.72         59.95
1236       DRAMA        58.46         59.95
1237       COMEDY       44.12         29.95
1238       DRAMA        58.46         89.95
1239       DRAMA        58.46         25.49
1245       ACTION       52.72         45.49
1246       COMEDY       44.12         58.29

任何帮助都表示赞赏。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您无法从您正在分组的同一查询中获取所有记录。计算一个查询中的平均值并加入表:

selecct
  m.MOVIE_NUM,
  m.MOVIE_GENRE,
  a.AVGCOST AS 'AVERAGE COST',
  m.MOVIE_COST
from
  MOVIE as m
  inner join (
    select MOVIE_GENRE, round(avg(MOVIE_COST)) as AVGCOST
    from MOVIE
    group by MOVIE_GENRE
  ) as a on a.MOVIE_GENRE = m.MOVIE_GENRE
order by MOVIE_NUM

答案 1 :(得分:1)

在mysql中执行此操作可能有更短的方法,因为它有一些巧妙的分组,但这应该有效:

Select
  m.Movie_Num,
  m.Movie_Genre,    
  gc.Average_Cost,
  m.Movie_Cost
From
  Movie m
    Inner Join (
      Select
        Movie_Genre,
        Round(Avg(Movie_Cost), 2) AS 'Average_Cost'
      From
        Movie
      Group By
        Movie_Genre
      ) as gc
     On m.Movie_Genre = gc.Movie_Genre
Order By 
  m.Movie_Num