如何使用group by编写sql查询

时间:2015-02-03 21:24:20

标签: sql database

我有这张桌子:

actors(id: int, first_name: string, last_name: string, gender: string)
directors(id: int, first_name: string, last_name: string)
directors genres(director id: int, genre: string, prob: 
float)
movies(id: int, name: string, years: int, rank: 
float,)
movies directors(director id: int, movie id: int)
movies genres(movie id: int, genre: string)
roles(actor id: int, movie id: int, role: string)

我想找到每种类型的年份,其中制作了该类型的最大电影。

我正在做以下但是我被困住了,请帮忙!

select m.YEAR, count(m.year) as c, genre 
from movies_genres, 
     movies m 
where m.id = movies_genres.movie_id 
group by genre, m.year;

2 个答案:

答案 0 :(得分:1)

你每年都会得到每种类型的电影数量,这很棒。现在,您只需要将查询作为派生表来选择最大值。

select genre, year, max(c) mc
from
    (select m.YEAR, count(m.year) as c, genre 
    from movies_genres mg
         inner join movies m
             on m.id = mg.movie_id 
    group by genre, m.year)
group by genre, year

答案 1 :(得分:0)

如果您使用的是SQL Server或Oracle或DB2,则应该可以使用。

SELECT genre, year, number
FROM 
(
  SELECT genre, year, number,
         row_number() over (PARTITION BY genre ORDER BY number DESC) as rank
  FROM
  (
    SELECT mg.genre, m.year, count(*) as number
    FROM movies_genres mg
    JOIN movies m on m.id = mg.movie_id
    GROUP BY mg.genre, m.year
  ) A
) B
WHERE rank = 1

它如何运作:从内到外,首先你得到所有类型和年份的计数。然后按计数对每个类型的年份进行排名,最后选择最大的项目。