SQL查询以组合过滤两个字段

时间:2012-02-29 14:15:25

标签: tsql

ArticleNumber   Company Storage
 01-01227       12      2
 01-01227       2       1  'filtered by company/storage in combination
 01-01227       5       1
 01-01227       12      1  'filtered by company/storage in combination
 01-44444       5       4  'filtered by not match the articlenumber

我想过滤包含(company = 12 storage = 1)和(company = 2 storage = 1的行)将从结果集中过滤掉,并过滤articlenr

这就是我提出的问题,但确定必须有一种更简单的方法来进行查询?

SELECT  * FROM    MyTable 
where 
    (Company=2 and Storage<>1 and ArticleNumber='01-01227') 
or 
    (Company=12   and Storage<>1 and ArticleNumber='01-01227') 
or
    (Company<>2 and Company<>12 and ArticleNumber='01-01227') 

我追求的结果:

ArticleNumber   Company Storage
  01-01227      12      2
  01-01227      5       1

5 个答案:

答案 0 :(得分:1)

SELECT * FROM MyTable
WHERE ArticleNumber='01-01227'
AND (Company NOT IN (2,12) OR Storage <> 1)

答案 1 :(得分:0)

让这更容易的一种可能方法是设置一个名为company_storage_exclude的表,其中包含CompanyStorage列。然后,只需使用要排除的CompanyStorage对填充这些值,然后就可以执行以下操作:

select *
from MyTable
where (Company,Storage) not in (select Company,Storage from company_storage_exclude)
and ArticleNumber='01-01227';

或:

select a.*
from MyTable a
left join company_storage_exclude b
on (a.Company=b.Company and a.Storage=b.Storage)
where b.Company is null and b.Storage is null
and ArticleNumber='01-01227';

答案 2 :(得分:0)

SELECT * FROM MyTable 
WHERE 
    NOT (Company=12 and Storage=1) 
AND 
    NOT (Company=5 and Storage=1)
AND
    ArticleNumber='01-01227'

甚至更好

SELECT * FROM MyTable 
WHERE 
    NOT ((Company=12 OR Company=5) AND Storage=1)
AND
    ArticleNumber='01-01227'

答案 3 :(得分:0)

这些方面的东西?

SELECT  * FROM    MyTable 
where 
    ArticleNumber='01-01227'
AND
    (Company IN (2,12) AND Storage <> 1
    OR
    Company NOT IN (2,12)
    )

答案 4 :(得分:0)

这将返回您要找的内容:

select * from t
where articleNumber = '01-01227' and (
  (company != 12 or storage != 1) and
  (company !=  2 or storage != 1)
)

结果:

ARTICLENUMBER   COMPANY STORAGE
01-01227        12      2
01-01227        5       1

没有必要加入这个解决方案,这使它保持非常快速和高效。此外,您可以轻松地成对添加重新加入。