从表中选择数据但不包括

时间:2012-04-23 09:23:13

标签: sql

我有一张这样的表:

NAME, SURNAME, TIME_SESSION

John, White, Morning
John, White, Evening
Alexander, Black, Morning
Carl, Yellow, Morning
Carl, Yellow, Afternoon
James, Red, Morning
James, Red, Evening

我必须从这张表中选取time_session ='Morning'的所有元素,但不要拿起也有time_session ='Evening'或time_session ='Afternoon'的记录。结果必须在此示例中:

Alexander, Black, Morning.

欢迎任何建议。

3 个答案:

答案 0 :(得分:3)

对同一个表进行左连接,并检查它们是否匹配:

select NAME, SURNAME, TIME_SESSION
from TheTable t1
left join TheTable t2 on t2.NAME = t1.NAME and t2.TIME_SESSION = 'Evening'
left join TheTable t3 on t3.NAME = t1.NAME and t3.TIME_SESSION = 'Afternoon'
where t1.TIME_SESSION = 'Morning' and t2.NAME is null and t3.NAME is null

答案 1 :(得分:3)

或者(与Guffa的回复不同的方法),您可以使用IF EXISTS()的单个查询:

SELECT Name, Surname, Time_Session
FROM dbo.YourTable t1
WHERE t1.Time_Session = 'Morning'
AND NOT EXISTS (SELECT * FROM dbo.YourTable t2 
                WHERE t1.NAME = t2.Name AND t1.Surname = t2.Surname 
                  AND t2.Time_Session IN ('Afternoon', 'Evening'))

答案 2 :(得分:1)

如果您正在寻找拥有一个而不是一个或多个其他人的人..

SELECT * 
FROM myTable AS t
WHERE 
    TIME_SESSION = 'Morning'
    AND NOT EXISTS (
        SELECT * FROM myTable AS s
        WHERE 
            s.NAME = t.NAME
            AND s.SURNAME = t.SURNAME
            AND s.TIME_SESSION IN ('Afternoon')
        )

如果您正在寻找只有一个条目的人

SELECT
    NAME, SURNAME
FROM 
    myTable 
GROUP BY 
    NAME, SURNAME
HAVING COUNT(*) = 1

然后您可以加入:

SELECT 
    t.*
FROM
    myTable AS t
    INNER JOIN (
            SELECT
                NAME, SURNAME
            FROM 
                myTable 
            GROUP BY 
                NAME, SURNAME
            HAVING COUNT(*) = 1
    ) AS l ON l.NAME = t.NAME AND l.SURNAME=t.SURNAME