sql查询获取合作的次数

时间:2013-01-03 12:18:40

标签: sql

我需要SQL查询的帮助。我有这个连接表,有22486行。

idPerson是从事电影工作的人,pesonType'1'是演员,'2'是导演。我需要得到导演和演员以及他们合作的电影数量。

例如,导演idPeroson = 3与2个电影中的演员idPerson = 14合作。

| idFilm | idPerson | peronType |
+---------+---------+--------+
| 1       | 14      | 1      |
| 1       | 3       | 2      |
| 1       | 34      | 1      |
| 2       | 3       | 2      |
| 2       | 14      | 1      |
+---------+---------+--------+

我会因此而发疯。非常感谢你。抱歉英语不好

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT DISTINCT
  d.idPerson AS Director,
  p.idPerson AS Actor,
  (SELECT COUNT(p2.idfilm)
   FROM Persons p2
   INNER JOIN Persons d2  ON p2.idFilm = d2.idFilm 
   AND d2.peronType = 2
   WHERE p2.peronType = 1
     AND p2.idperson = p.idperson
     AND d2.idperson = d.idperson ) Counts
FROM Persons p
INNER JOIN Persons d  ON p.idFilm = d.idFilm 
                     AND d.peronType = 2
WHERE p.peronType = 1;

SQL Fiddle Demo

这会给你:

| DIRECTOR | ACTOR | COUNTS |
-----------------------------
|        3 |    14 |      2 |
|        3 |    34 |      1 |

答案 1 :(得分:2)

获得同样好结果的更有效方法是:

SELECT
  D.idPerson Director,
  P.idPerson Actor,
  count(1) NBFilm
FROM       Persons D
INNER JOIN Persons P ON D.idFilm = P.idFilm 
WHERE P.peronType = 1
  AND D.peronType = 2
GROUP BY  D.idPerson, P.idPerson

所以你只有一个内部联接。 select中的子查询可能非常划算。

答案 2 :(得分:0)

这将为你提供制作电影数量的人,

select idperson,count(distinct idfilm) NoOfFilms,
case when persontype=2 then 'Director' else 'Actor' end Profession
from table1
group by idperson

SQL_LIVE_DEMO

示例输出:

    IDPERSON    NOOFFILMS   PROFESSION
        3             2      Director
       14             2      Actor
       34             1       Actor