SQL计数多行

时间:2013-03-05 20:37:19

标签: sql postgresql count

我有以下内容:

SELECT nominees.personname, awards.name as awards, nominees.filmname 
FROM nominees, awards WHERE nominees.aid = awards.aid and nominees.personname is not 
NULL GROUP BY nominees.personname, awards.name, nominees.filmname 
ORDER BY nominees.personname;

这会产生下表:

"personname"    "awards"        "filmname"

"Ang Lee"       "director"      "Life of Pi"
"Anglelina J."  "actress"       "The Tourist"
"Ann Dowd"   "supporting actress"   "Compliance"
"Anne Hathaway" "actress"      "Love and Other Drugs"
"Anne Hathaway" "supporting actress"  "Les Misrables"
"Annette Bening"    "actress"   "The Kids Are All Right"
"Another Year"  "screenplay"    "Mike Leigh"
"A.R. Rahman"     "score"       "127 Hours"
"AR Rahman"       "score"       "127 Hours"
"Barbara Hershey"   "supporting actress"    "Black Swan"
"Ben Affleck"   "actor"         "Argo"
"Ben Affleck"   "director"      "Argo"

我正试图获得仅包含因同一部电影而被提名为两个单独奖项的人的集合。在这张特别的表中,只有'本阿弗莱克'。

结果应为

    "personname"    "awards"        "filmname"

    "Ben Affleck"   "actor"         "Argo"
    "Ben Affleck"   "director"      "Argo"

但我似乎无法理解,我已经尝试过使用HAVING和某种计数方法,但却无法实现这一点。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:3)

这是简单的聚合查询。让这个人做:

select personname, filmname
from (SELECT nominees.personname, awards.name as awards, nominees.filmname 
      FROM nominees, awards WHERE nominees.aid = awards.aid and nominees.personname is not NULL
      GROUP BY nominees.personname, awards.name, nominees.filmname 
     ) t
 group by personname, filmname
 having count(*) > 1

您可以根据原始数据对此进行短语,并将列表放在一行中:

SELECT nominees.personname, nominees.filmname, array_agg(awards.name) as listOfaward
FROM nominees join
     awards
     on nominees.aid = awards.aid
where nominees.personname is not NULL
GROUP BY nominees.personname, nominees.filmname 
having COUNT(distinct  awards.name) > 1

要为每个奖项分别获取一行,您可以加入原始数据:

select personname, filmname, a.name
from (SELECT nominees.personname, nominees.filmname, array_agg(awards.name) as listOfaward
      FROM nominees join
           awards
           on nominees.aid = awards.aid
      where nominees.personname is not NULL
      GROUP BY nominees.personname, nominees.filmname 
      having COUNT(distinct  awards.name) > 1
     ) l join
     nominees n
     on n.personname = l.personname and n.filmname = l.filmname join
     awards a
     on n.aid = a.aid

答案 1 :(得分:0)

我认为它应该是这样的:

SELECT nominees.personname, awards.name as awards, nominees.filmname, count(distinct  awards.name) as number_awards
FROM nominees, awards WHERE nominees.aid = awards.aid and nominees.personname is not 
NULL 
GROUP BY nominees.personname, awards.name, nominees.filmname 
HAVING number_awards > 1
ORDER BY nominees.personname;
相关问题