SQL查找唯一值

时间:2016-10-31 11:33:50

标签: sql unique

我试图找到一个选择唯一值的语句。 不像不同/唯一,因为这些只是删除重复。我想获得所有唯一值的列表,只有一个条目。

例如:

值:1,2,3,4,4,5,5,6。

我想得到:1,2,3,6。

编辑:

问题是: 哪些演员(电影的名称和数量)在超过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) |

这是我到目前为止所尝试过的,虽然我甚至不接近我认为的解决方案:

SELECT p.firstname, COUNT(fp.filmid)
FROM person p INNER JOIN filmparticipation fp
ON p.personid = fp.personid
INNER JOIN filmcharacter fc
ON fc.partid = fp.partid
GROUP BY p.firstname
HAVING COUNT(fc.filmcharacter) = 1;

谢谢。

2 个答案:

答案 0 :(得分:4)

一种简单方法使用group byhaving

select val
from t
group by val
having count(*) = 1;

答案 1 :(得分:0)

你想要计算每个演员和角色的电影,所以你必须按这两个分组。

select p.personid, p.firstname, p.lastname, fc.filmcharacter, count(distinct fp.filmid)
from person p
join filmparticipation fp on fp.personid = p.personid
join filmcharacter fc on fc.partid = fp.partid
group by p.personid, p.firstname, p.lastname, fc.filmcharacter
having count(distinct fp.filmid) > 199;

即使你只对那些在至少200部电影中扮演某些角色的演员感兴趣(即无论是哪个角色,或者只是一个角色还是多个角色),你都要先做同样的事情,然后再将其煮沸每个演员的唯一行数:

select distinct p.personid, p.firstname, p.lastname
from person p
join filmparticipation fp on fp.personid = p.personid
join filmcharacter fc on fc.partid = fp.partid
group by p.personid, p.firstname, p.lastname, fc.filmcharacter
having count(distinct fp.filmid) > 199;
相关问题