2015-10-26 102 views
1

我有一个包含id,type的表。选择记录中只有特定值的所有行

我希望选择只具有一个或多个记录的相同类型的ID。

例如,

假设这是我的表:

id type 
456  4 
123  4 
123  4 
123 18 
123  4 
789  4 
789  4 
000  7 

我想IDS:456789原因而IDS只有类型= 4的记录:

456有一个创纪录,并且789具有两个类型= 4的记录。

123具有类型= 4,但具有类型= 18。

我该怎么办?

我知道我可以使用分区,但我想是加入/存在..

http://sqlfiddle.com/#!9/731e1

+1

所以,你要选择那里并没有'用相同的ID,但不同类型的exist'另一行的所有行?嗯,我不知道你怎么可以这样做... –

回答

4

您可以使用:

SELECT id 
FROM cards 
GROUP BY id 
HAVING MIN(type) = MAX(type) 

Demo here

+1

哇,我正在考虑与存在的子查询,但这..远远好得多。 –

+0

它不SQL服务器上运行,但它只是对sqlFiddle: SELECT ID,类型,状态 从银行卡 GROUP BY ID HAVING MIN(类型)= MAX(型)和类型= 4 –

+0

你为什么添加'HAVING'子句中的'type = 4'? –

3
Select Id 
FROM cards 
GROUP BY Id 
HAVING COUNT(DISTINCT [type]) = 1 
+1

我喜欢这个,因为它可以很容易地被修改来查找只有两个或最多两种类型的Ids。 – trincot

0

我不要以为@ M.Ali回答你的标准。他的结果集包括ID =“000”

if OBJECT_ID('Tempdb..#Work') is not null 
    drop table #Work; 
Create Table #Work (Id char(3), [Type] int) 
insert into #Work values 
('456', 4) 
, ('123', 4) 
, ('123', 4) 
, ('123', 18) 
, ('123', 4) 
, ('789', 4) 
, ('789', 4) 
, ('000', 7) 

select distinct * 
from #Work a 
where exists (
       select Type 
        ,Count(Distinct Id) cntId 
       from #Work b 
       where a.Type = b.Type 
       group by Type 
       having Count(Distinct Id) > 1 
      ) 
and exists (
     select Id 
      ,count(distinct Type) 
     from #Work c 
     where a.Id = c.Id 
     group by id 
     having count(distinct type)= 1 
    ) 

输出:

Id Type 
---- ----------- 
456 4 
789 4 
相关问题