如果任何行符合条件,请选择否行?

时间:2015-07-23 14:43:57

标签: sql tsql

如果结果集中的任何行符合某个条件,如何选择无行?

例如:

Id|SomeColumn|Indicator
1 | test     | Y
1 | test1    | Y
1 | test2    | X
2 | test1    | Y
2 | test2    | Y
3 | test1    | Y

假设我想要选择Id = 1的所有行,除非有一行指示符= X

目前我正在做这样的事情

SELECT * FROM SOMETABLE WHERE ID = 1 AND INDICATOR = 'Y' AND ID NOT IN (SELECT ID WHERE INDICATOR = 'X')

但这感觉非常笨重,我觉得可能有更好的方法来做到这一点。我或者只是过于敏感

3 个答案:

答案 0 :(得分:2)

这样的东西?

SELECT * 
FROM SOMETABLE 
WHERE ID = 1 
AND NOT EXISTS (SELECT 1 FROM SOMETABLE WHERE INDICATOR = 'X')

或者,如果您希望X仅区分相同的id:

SELECT * 
FROM SOMETABLE t1
WHERE t1.ID = 1 
AND NOT EXISTS (SELECT 1 FROM SOMETABLE t2 WHERE t1.ID = t1.ID AND INDICATOR = 'X')

答案 1 :(得分:1)

没有太多选择可以做到这一点。另一种选择是使用EXISTS

SELECT * 
FROM SOMETABLE s1 
WHERE ID = 1 AND INDICATOR = 'Y' 
     AND NOT EXISTS (SELECT TOP 1 ID FROM SOMETABLE s2 WHERE s1.ID = s2.ID AND INDICATOR = 'X')

答案 2 :(得分:1)

另一种选择,假设指标栏中有强制订单。

DECLARE @T TABLE
    (
      ID INT
    , someColumn VARCHAR(5)
    , Indicator CHAR(1)
    )
INSERT  INTO @T
        ( ID, someColumn, Indicator )
VALUES  ( 1, 'test', 'Y' ),
        ( 1, 'test1', 'Y' ),
        ( 1, 'test2', 'X' ),
        ( 2, 'test1', 'Y' ),
        ( 2, 'test2', 'Y' ),
        ( 3, 'test1', 'Y' )

SELECT t.ID
       , t.someColumn
       , t.Indicator
FROM @T t
    JOIN (SELECT ID
            FROM @T t2
            GROUP BY t2.ID
            HAVING MIN(indicator) >= 'Y') q ON q.ID = t.ID

不确定它是否不那么笨重,但它可能表现更好,因为它使用正面排除而非负面。