-1

这是场景。我有一个 SQL Server 2008 表 - 产品 - 有 2 列:id 和 IsNotValid。数据看起来像这样:

id     IsNotValid
1        0
1        0
1        1
2        0
2        0
3        1
3        1

我想要一个 SQL 语句,该语句将返回一个结果集,该结果集将返回 id=2 的所有记录 (2) - 在这种情况下,id=2 的所有 IsNotValid 值都是 0。id=1 不应作为一个返回其 IsNotValid 记录数为 1。对于 id=3 类似。数据类型有:id(int)、IsNotValid(bit)。

4

4 回答 4

3

这里有一些方法

Declare @t table (Id Int, IsnotValid Bit)
Insert Into @t Values(1,0),(1,0),(1,1),(2,0),(2,0),(3,1),(3,1)

方法一:

SELECT * FROM @t WHERE Id NOT IN (SELECT Id FROM @t WHERE IsnotValid=1) 

方法二:

SELECT * 
FROM @t T1 
WHERE IsnotValid = 0 
AND NOT EXISTS ( 
    SELECT *  
    FROM @t T2  
    WHERE T1.Id = T2.Id 
    AND T2.IsnotValid <> 0) 

方法3:

SELECT * 
FROM @t T1 
WHERE IsnotValid = 0 
AND Id NOT IN ( 
    SELECT Id  
    FROM @t T2  
    WHERE T2.IsnotValid <> 0) 

方法4:

SELECT T1.* 
FROM @t T1 
LEFT OUTER JOIN @t T2 ON T1.Id = T2.Id AND T2.IsnotValid <> 0 
WHERE T1.IsnotValid = 0 
AND T2.Id IS NULL 

方法5:

select Id,IsnotValid
from (select t.*, SUM(CAST(IsnotValid AS INT)) over (partition by Id) as sumflag 
      from @t t 
     ) t 
where sumflag = 0 

方法6:

;with cte as( 
    Select  
        Id = Case when x.Id is null then y.Id else x.Id end  
        ,x.CountFor0 
        ,y.CountFor1 
    From  
            (Select Id,CountFor0 = count(*) 
            from @t  
            where IsnotValid = 0 
            group by Id )x 
    Full Join  

            (Select Id,CountFor1 =count(*) 
            from @t  
            where IsnotValid = 1 
            group by Id )y 
    On x.Id = y.Id) 

    Select Id 
    From cte 
    where CountFor1 is null 

结果

Id  IsnotValid
2   0
2   0
于 2012-10-18T04:36:01.090 回答
3

这应该会给你你需要的结果:

SELECT * FROM Products WHERE id NOT IN
(SELECT id FROM Products WHERE IsNotValid = 1)
于 2012-10-18T00:13:11.003 回答
1

如果你尝试了一些东西并展示了你尝试过的东西,那就太好了。

因为 0 代表“好”而 1 代表“坏”,我会这样做

SELECT id FROM yourtable GROUP BY id HAVING SUM( IsNotValid ) = 0

这将仅列出所有 IsNotValid 为零的这些 id。

于 2012-10-18T00:18:01.687 回答
0

这是另一种方法:

-- using CTE and a join
with MyCte as
(
select id from Products 
where IsNotValid = 1
group by id
)
select a.* from Products a
    left join MyCte b
    on a.id = b.id
where b.id is null
于 2012-10-18T00:20:53.183 回答