SQL不止一次检查类似的项目

时间:2012-06-14 02:36:43

标签: sql join

架构

Movie(title, year, director, budget, earnings)
Actor(stagename, realname, birthyear)
ActedIn(stagename, title, year, pay)
CanWorkWith(stagename, director)

寻找不止一次使用的电影片头(SQL Robot DEATH MACHINE 2001,2002,2039)

SELECT M.title
FROM Movie A
LEFT JOIN Movie M ON M.title = A.title AND A.year <> A.year
WHERE M.title IS NULL

因此,当它找到另一个已在不同年份使用的标题时,它将显示电影的标题

3 个答案:

答案 0 :(得分:1)

SELECT
    title
FROM
    Movie
GROUP BY
    title
HAVING
    COUNT(*) > 1

答案 1 :(得分:1)

假设SQL 2008r2并且电影基于Title,Year,Director是唯一的:

;with cte as (
    Select *, count(*) over(partition by Title) dups
    From movie
)
Select * 
From cte
Where dups> 1

返回已使用多次的所有电影标题。如果您想将它限制在同一年具有相同标题的电影中,只需将其添加到分区。

答案 2 :(得分:0)

Select M.Title
From Movie As M
Where Exists    (
                Select 1
                From Movie As M1
                Where M1.Title = M.Title
                    And M1.Year <> M.Year
                )