有趣的SQL问题

时间:2009-11-20 21:26:08

标签: sql sql-server-2005 tsql

我正在尝试消化SQL问题。我正在使用SQL Server 2005。

在表格中,我有这样的数据:

ID     Type
1        A
2        A
3        A
3        B
4        B

我需要找到所有类型都是A和B的ID。

10 个答案:

答案 0 :(得分:12)

使用INTERSECT operator

   SELECT DISTINCT ID FROM [Table] WHERE Type = 'A'
   INTERSECT
   SELECT DISTINCT ID FROM [Table] WHERE Type = 'B'

答案 1 :(得分:11)

select distinct a.id 
from table a
join table b on a.id=b.id
where a.type='A'
and b.type='B';

答案 2 :(得分:2)

使用半连接(无排序,仅在B上搜索索引):

select a.id from table a
    where a.type = 'A'
      and exists (select * from table b where a.id = b.id and b.type = 'B')

答案 3 :(得分:1)

如果您想稍微抽象一下问题并找到具有相同ID的行在类型列中包含不同值的情况,您可以检查<>像这样:

DECLARE @TestTable TABLE (thisid int, thisval varchar(1))

INSERT INTO @TestTable VALUES  (1, 'A')
INSERT INTO @TestTable VALUES  (2, 'A')
INSERT INTO @TestTable VALUES  (3, 'A')
INSERT INTO @TestTable VALUES  (3, 'B')
INSERT INTO @TestTable VALUES  (4, 'B')

SELECT DISTINCT thisid
FROM @TestTable a
WHERE EXISTS
( SELECT * 
FROM @TestTable b
WHERE a.thisid=b.thisid AND a.thisval<>b.thisval)
-- www.caliberwebgroup.com

返回:

3

答案 4 :(得分:1)

select id, count(type = 'A') as a_count, count(type = 'B') as b_count
from your_table
group by 1
having a_count > 0 and b_count > 0;

至少,这适用于理智的SQL环境。 Dunno,如果它适用于你的。

答案 5 :(得分:0)

我没有看其他答案,但仍在发帖。洛尔

SELECT distinct t1.ID
FROM table1 AS t1
WHERE exists 
   (select t2.ID from table1 t2 where t2.type="A" and t2.ID=t1.ID) 
   and exists 
   (select t3.ID from table1 t3 where t3.type="B" and t3.ID=t1.ID);

答案 6 :(得分:0)

SELECT Id FROM tableX AS x,tableX AS y WHERE x.id = y.id AND x.type ='A'AND y.type ='B'

答案 7 :(得分:0)

这很简单

Declare @t table([ID] INT, [Type] VARCHAR(2))
INSERT INTO @t SELECT 1, 'A' UNION ALL SELECT 2,'A' UNION ALL SELECT 3,'A' 
UNION ALL SELECT 3,'B' UNION ALL SELECT 4,'B' UNION ALL SELECT 5,'A' UNION ALL SELECT 5,'A'

;WITH CTE AS
(
    SELECT Rn = Row_NUMBER() OVER(PARTITION BY [ID],[TYPE] ORDER BY [ID])
    ,*
    FROM @t
)
SELECT ID 
FROM CTE 
WHERE Rn =1 AND ([Type]='A' or [Type]='B')
GROUP BY [ID]
HAVING (COUNT([ID])>1)

<强>输出:

<强> ID

3

答案 8 :(得分:-1)

如果存在“未知”数量的类型并且您想要找到所有类型的所有ID,这将有所帮助

select id from yourtable group by id having count(*)=(select  count(distinct type) from yourtable)

答案 9 :(得分:-1)

select id
from idtypedata
group by id
having 
sum(
    case type
        when 'A' then 1
        when 'B' then 2
        -- when 'C' then 4
        -- when 'D' then 8
    end
    ) & 1 = 1
And 
sum(
    case type
        when 'A' then 1
        when 'B' then 2
        -- when 'C' then 4
        -- when 'D' then 8
    end
    ) & 2 = 2