带有交叉行WHERE语句的SELECT查询

时间:2013-09-06 14:10:32

标签: sql sql-server

我将尝试解释我想要的查询类型:

假设我有一个这样的表:

| ID | someID | Number |
|----|--------|--------|
| 1  | 1      | 10     |
| 2  | 1      | 11     |
| 3  | 1      | 14     |   
| 4  | 2      | 10     |  
| 5  | 2      | 13     | 

现在,我想找到具有特定数字的someID(例如,查询数字10,11,14将返回someID 1并查询数字10,13将返回2)。但是,如果someID包含所有查询号但是包含更多数字,则查询不会返回。 (例如查询10,11将不返回任何内容) 有可能吗?

3 个答案:

答案 0 :(得分:2)

select someID
from yourtable
where number in (10,11,14)
and not exists (select * from yourtable t2 where number not in(10,11,14) 
                 and t2.someid=yourtable.someid)
group by someID
having count(distinct ID) = 3

3是您要查询的项目数

答案 1 :(得分:2)

SELECT t1.someId
FROM yourTable t1
WHERE t1.number IN (10,14,11)
GROUP BY t1.someID
HAVING COUNT(DISTINCT t1.ID) = (SELECT COUNT(DISTINCT t2.ID) FROM yourTable t2 WHERE t1.someID=t2.someID)

Example Fiddle

答案 2 :(得分:1)

是的,一旦您将查询号码输入表变量(比如称为@QNums,其中一列名为QNum),请尝试

 Select distinct someId
 From table t
 Where exists (Select * from @QNums
               where QNum = t.Number)
   And not Exists (Select * From table t2
                   Where someId = t.someId
                      And not exists(Select * From @QNums
                                     where QNum = t3.Number))