MS SQL:SELECT field1,来自[table]的field2,其中field2 = IN(' val1',val2')当field1 =' value2'

时间:2015-10-07 12:13:44

标签: sql sql-server database subquery

我目前在过滤SQL记录方面遇到了麻烦。我需要类似以下概念的结果:

我希望根据同一个表中另一个字段的结果显示某些记录的结果。比如说,如下所示:

SELECT [Field1], [field2] 
FROM [table]
WHERE [Field1] IN ('value1', 'value2')
--from 'value2' i need to filter or remove some records 
WHERE [field2] NOT IN ('val1','val2') When [Field1] is 'value2'

我已经花了很多时间在这上面我仍然无法做正确的事情。 我很感激你的帮助。

4 个答案:

答案 0 :(得分:1)

两个字段的逻辑点。

   SELECT [Field1], [field2] 
     FROM [table]
    WHERE [Field1] IN ('value 1' , ... ) -- Other non value 2 values
       OR (Field1 = 'Value 2' AND [field2] NOT IN ('val1','val2'))

答案 1 :(得分:1)

您需要为每个条件分离逻辑。

SELECT  [Field1], [field2] 
FROM    [table]
WHERE   ([Field1] = 'value2' AND [field2] NOT IN ('val1','val2'))
OR      ([Field1] = 'value1')

答案 2 :(得分:1)

不清楚你真正想要的是什么。

但我的猜测

SELECT [Field1], [field2] FROM [table]
WHERE [Field1] in ('value1', 'value2')
and [field2] !=(case 
when [Field1]='value1' THEN 'val1'
when [Field1]='value2' THEN 'val2'

.
.
.
End)

答案 3 :(得分:1)

从最佳答案(@ Siyual's)开始,您可以对其进行优化以减少维护:

SELECT  [Field1], [field2] 
FROM    [table]
WHERE   ([Field1] = 'value2' AND [field2] NOT IN ('val1','val2'))
OR      ([Field1] = 'value1')

使用[Field1] = 'value1'[Field1] in('value1', 'value3', 'value...', 'valueN')表示无论何时将新值放入[Field1],您的查询都会中断。用[Field1]!='value2'代替你会更好,给你:

SELECT  [Field1], [field2] 
FROM    [table]
WHERE   ([Field1] = 'value2' AND [field2] NOT IN ('val1','val2'))
OR      ([Field1] != 'value2')

从那里,您也可以应用逻辑运算符来实现您所说的WHERE (A && B) || !A,在这种情况下,XOR或OR之间没有区别,这意味着它等同于WHERE (!A)||B ,它给你:

SELECT  [Field1], [field2] 
FROM    [table]
WHERE   ([Field1] != 'value2') OR [field2] NOT IN ('val1','val2'))