根据另一列获取最小出现次数

时间:2012-10-23 18:17:30

标签: mysql sql

问题:有多少部电影的演员人数最少?

表:

title | year | person | role (actor, director, writer, producer)

我做了什么:

SELECT title, count(role) 
FROM movie_table 
where role='actor' 
GROUP BY title 
ORDER by count(role) ASC;

我得到了什么:

title (007, Dark Knight, Superman, Batman ...) | count(role) (1, 1, 2, 2,...)

我需要的是一种用minium actor角色计算电影的方法,在这种情况下是2(007和黑暗骑士)。

1 个答案:

答案 0 :(得分:1)

目前还不是很清楚你想要什么,但似乎你要求这个:

SELECT title, count(role) 
FROM movie_table 
where role='actor' 
GROUP BY title 
HAVING count(role) = 1
ORDER by count(role) ASC;

根据您的评论,您可以使用以下内容:

SELECT title
FROM movie_table 
where role='actor' 
GROUP BY title 
HAVING count(role) = (select min(cnt)
                      from (select count(role) cnt
                            from movie_table
                            group by title) c)
ORDER BY count(role);

请参阅SQL Fiddle with Demo

如果您那么,只需要总计,请将count()函数应用于查询:

select count(title) Total
from
(
  SELECT title
  FROM movie_table 
  where role='actor' 
  GROUP BY title 
  HAVING count(role) = (select min(cnt)
                        from (select count(role) cnt
                              from movie_table
                              group by title) c)
) x

请参阅SQL Fiddle with Demo