查询:查找不属于值列表的行

时间:2010-07-08 12:30:08

标签: sql sql-server sql-server-2005

让我们考虑我有一个表'Tab',它有一个'Col'列

表'Tab'有这个数据 -

Col
1
2
3
4
5

如果我有一组值(2,3,6,7)。我可以通过起诉查询

来查询表和列表中存在的值
Select Col from Tab where col IN (2,3,6,7)

但是,如果我想返回列表中不存在于表中的值,即在这种情况下仅返回(6,7)。我应该使用什么查询?

7 个答案:

答案 0 :(得分:3)

SQL Server 2008方法

SELECT N FROM (VALUES(2),(3),(6),(7)) AS D (N)
EXCEPT
Select Col from Tab

或SQL Server 2005

DECLARE @Values XML

SET @Values = 
'<r>
    <v>2</v>
    <v>3</v>
    <v>6</v>
    <v>7</v>
</r>' 


SELECT 
    vals.item.value('.[1]', 'INT') AS Val
FROM @Values.nodes('/r/v') vals(item)
EXCEPT
Select Col from Tab

答案 1 :(得分:3)

我相信的问题是你试图在声明中找到你的价值观。您需要做的是将您的in语句转换为表格,然后您可以确定哪些值不同。

create table #temp
(
value int
)

insert into #temp values 1
insert into #temp values 2
insert into #temp values 3
insert into #temp values 4

select
 id
from
 #temp
where
 not exists (select 1 from Tab where Col = id)

更好的选择是创建一个表值函数,将逗号分隔的字符串转换为表格。我没有任何代码方便,但在Google上应该很容易找到。在这种情况下,您只需要使用以下语法。

select
 id
from
 dbo.SplitStringToTable('2,3,6,7')
where
 not exists (select 1 from Tab where Col = id)

希望这有帮助

答案 2 :(得分:2)

一种方法是使用临时表:

DECLARE @t1 TABLE (i INT) 
INSERT @t1 VALUES(2) 
INSERT @t1 VALUES(3)
INSERT @t1 VALUES(6) 
INSERT @t1 VALUES(7)

SELECT i FROM @t1 WHERE i NOT IN (Select Col from Tab)

答案 3 :(得分:0)

一种方法是

declare @table table(col int)
insert into @table
select 1 union all
select 2  union all
select 3  union all
select 4  union all
select 5 


declare @t table(col int)
insert into @t
select 2 union all
select 3 union all
select 6 union all
select 7 

select t1.col from @t as t1 left join @table as t2 on t1.col=t2.col
where t2.col is null

答案 4 :(得分:0)

您的数据库中有[数字]表吗? (见Why should I consider using an auxiliary numbers table?

SELECT
    [Tab].*
FROM
    [numbers]
    LEFT JOIN [Tab]
        ON [numbers].[num] = [Tab].[Col]
WHERE
    [numbers].[num] IN (2, 3, 6, 7)
    AND [Tab].[Col] IS NULL

答案 5 :(得分:0)

我认为有很多方法可以实现这一点,这里有一个。

SELECT a.col 
FROM 
  (SELECT 2 AS col UNION ALL SELECT 3 UNION ALL SELECT 6 UNION ALL SELECT 7) AS a
WHERE a.col NOT IN (SELECT col FROM Tab)

答案 6 :(得分:0)

晚会......

SELECT 
    '2s' = SUM(CASE WHEN Tab.Col = 2 THEN 1 ELSE 0 END),
    '3s' = SUM(CASE WHEN Tab.Col = 3 THEN 1 ELSE 0 END),
    '6s' = SUM(CASE WHEN Tab.Col = 6 THEN 1 ELSE 0 END),
    '7s' = SUM(CASE WHEN Tab.Col = 7 THEN 1 ELSE 0 END)
FROM
(SELECT 1 AS Col, 'Nums' = 1 UNION SELECT 2 AS Col,'Nums' = 1 UNION SELECT 3 AS Col,      'Nums' = 1 UNION SELECT 4 AS Col, 'Nums' = 1 UNION SELECT 5 AS Col, 'Nums' = 1 ) AS Tab
GROUP BY Tab.Nums

顺便说一句,我的也给出了每个的计数,如果你需要的话很有用。就像您根据库存中的内容检查产品列表一样。虽然你可以更好地编写一个支点,但不知道我的头脑是多么偏离。