MSSQL - 检查其他值不存在的位置

时间:2014-04-03 11:28:19

标签: sql-server

相对简单(我认为),但我不太清楚如何做到这一点。

我有一组数据,我想要返回结果错误的ID,例如在下面的集合中,只应返回100。应该排除200,因为它有“好”的结果。

    UID ID  Date/Time           Result
    1   100 02/04/2014 08:00    Bad
    2   200 02/04/2014 08:05    Bad
    3   100 03/04/2014 08:10    Bad
    4   100 03/04/2014 08:20    Bad
    5   200 03/04/2014 09:00    Bad
    6   200 03/04/2014 18:00    Good

由于

4 个答案:

答案 0 :(得分:1)

试试这个

SELECT ID FROM TABLE1
WHERE RESULT = 'BAD' AND 
      NOT EXISTS (SELECT * FROM WHERE RESULT = 'GOOD')

答案 1 :(得分:1)

翻译标题:使用NOT EXISTS

SELECT t.*
FROM dbo.TableName t
WHERE NOT EXISTS
(
   SELECT 1 FROM dbo.TableName t2
   WHERE t.ID = t2.ID AND t2.Result = 'Good'
)

Demo

ALL

SELECT t.*
FROM dbo.TableName t
WHERE 'Bad' = ALL(
   SELECT t2.Result FROM dbo.TableName t2
   WHERE t.ID = t2.ID 
)

Demo

答案 2 :(得分:0)

如果您想要完整的行,而不仅仅是ID,那么您可以使用几个窗口聚合:

declare @t table (UID int,ID int,dt datetime,Result varchar(19))
insert into @t(UID,ID,dt,Result) values
(1,100,'2014-04-02T08:00:00','Bad'),
(2,200,'2014-04-02T08:05:00','Bad'),
(3,100,'2014-04-03T08:10:00','Bad'),
(4,100,'2014-04-03T08:20:00','Bad'),
(5,200,'2014-04-03T09:00:00','Bad'),
(6,200,'2014-04-03T18:00:00','Good')

;With MinMax as (
    select *,
        MIN(Result) OVER (PARTITION BY ID) as minR,
        MAX(Result) OVER (PARTITION BY ID) as maxR
    from @t
)
select UID,ID,dt,Result from MinMax
where minR = maxR and minR = 'Bad'

因为当特定行的最小值和最大值相等时,您知道观察值的全部是相等的。

结果:

UID         ID          dt                      Result
----------- ----------- ----------------------- -------------------
3           100         2014-04-03 08:10:00.000 Bad
4           100         2014-04-03 08:20:00.000 Bad
1           100         2014-04-02 08:00:00.000 Bad

答案 3 :(得分:0)

您希望ID的不同值与良好结果无关吗? 像

这样的东西
SELECT DISTINCT ID
FROM   myTable
WHERE  ID NOT IN (SELECT ID FROM myTable WHERE Result = 'Good')

应该这样做。

如果"坏"的所有数据然后需要ID

SELECT *
FROM   myTable
WHERE  ID NOT IN (SELECT ID FROM myTable WHERE Result = 'Good')