【问题标题】:SQL find unique valuesSQL 查找唯一值
【发布时间】:2016-10-31 11:33:49
【问题描述】:

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

例如:

值: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;

谢谢。

【问题讨论】:

  • 使用 SELECT DISTINCT

标签: sql unique


【解决方案1】:

一个简单的方法使用group byhaving

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

【讨论】:

  • 好吧,这有点帮助。但是,我想找出哪些值(人)有超过 199 个唯一值(印章)。我可以使用其他计数来查找超过 199 的人吗?
  • @Br0dskive 您能否提供更详细的样本和结果来反映这一新要求?
  • @Br0dskive 。 . .你应该把它作为另一个问题来问。它与您的原始问题无关(除非having count(*) > 199 解决了您的问题)。
  • @GordonLinoff,是的,我很抱歉。我最初的问题有点不清楚。我问了一个新问题,我更详细地描述了这个问题。
【解决方案2】:

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

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;

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 2019-08-05
    • 1970-01-01
    • 2020-05-01
    • 2017-03-13
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多