如果一个记录包含NULL,则排除特定ID的所有记录

时间:2013-04-18 20:17:17

标签: sql-server-2008

如何排除与具有null值的行对应的所有行?

-----------------------------------
| 0000139 | null | 10-01-2012 |
----------------------------------
| 0000139 | 95 | 10-02-2012 |
-----------------------------------

我不仅要排除带有null的行,还要排除所有其他行。

2 个答案:

答案 0 :(得分:4)

;WITH x AS (SELECT key FROM dbo.table WHERE some_column IS NULL)
  SELECT col1, col2, etc.
  FROM dbo.table AS t
  WHERE NOT EXISTS (SELECT 1 FROM x WHERE key = t.key);

答案 1 :(得分:0)

以下代码标识了至少有一个测试分数为NULL值的所有孩子,并将其从查询结果中排除。

CREATE TABLE #Test
    ( KidId INT NOT NULL
    , Score INT NULL);

INSERT INTO #Test (KidId, Score)
SELECT KidId
    , Score
FROM (VALUES
        (1, 100), (1, 50), (1, 10)
    , (2, NULL), (2, NULL), (2, NULL)
    , (3, 100), (3, NULL), (3, 40)) sub (KidId, Score);

SELECT *
FROM #Test trgt
WHERE NOT EXISTS
    (SELECT 1
    FROM #Test src
    WHERE trgt.KidId = src.KidId
    AND src.Score IS NULL);