SQL查找连接到超过199个唯一值的值

时间:2016-10-31 13:20:05

标签: sql

我今天早些时候问this question,但我认为我不够清楚。

我的问题是: 哪些演员(电影的名称和数量)在超过199部电影中扮演了具有独特角色名称的角色?

我有这些表格:

Table "public.filmparticipation"
  Column  |  Type   | Modifiers 
----------+---------+-----------
 partid   | integer | 
 personid | integer | not null
 filmid   | integer | not null
 parttype | text    | not null


Table "public.filmcharacter"
    Column     |  Type   | Modifiers 
---------------+---------+-----------
 partid        | integer | 
 filmcharacter | text    | 
 billingpos    | integer |


Table "public.person"
  Column   |     Type     | Modifiers 
-----------+--------------+-----------
 personid  | integer      | 
 lastname  | text         | not null
 firstname | text         | 
 gender    | character(1) |

澄清问题: 我想找到所有演过超过199部电影的演员,他们的角色名称是独一无二的。这意味着他们在此电影中的角色名称尚未在数据库中的任何其他影片中使用。我想得到一个列表,其中包含演员的名字,以及他们在角色名称独特的地方播放的电影数量。结果看起来像这样(我使用了完全随机的值):

  Name     | Filmcharacter|
-----------+--------------+
 Pitt      | 465          | 
 Clooney   | 265          |
 Depp      | 320          | 
 Jolie     | 229          |

2 个答案:

答案 0 :(得分:0)

您可以使用join,count和having子句

select p.lastname, p.firstname, count(f.*) as Filmcharacter 
from person as p 
inner join filmparticipation as c on p.personid = c.personid 
inner join  filmcharacter as f on f.partid = c.partid
group by p.lastname, p.firstname
having count(*) > 199

答案 1 :(得分:0)

试试这个:

Select p.personId, p.firstName, p.LastName, count(*)
from public.Person p
   join public.filmparticipation fp
      on fp.personId = p.personId
             -- subquery ensures that the part has not been in any other film
         and (Select count(*) from public.filmparticipation
              where partId = fp.PartId) == 1
Group By p.personId, p.firstName, p.LastName
Having count(*) > 199    -- <-- this filters out actors in less than 199 films