SQL Query用于检索仅属于组的值

时间:2015-02-25 18:03:07

标签: sql oracle

假设我有一个包含以下值和列的表:

ID1 | ID2
1   | 1
2   | 1
3   | 1
4   | 1
4   | 2
3   | 3
4   | 3
4   | 4
4   | 4

我想将完全的ID2值检索到ID1 = 4的记录。因此,对于上面的示例,我希望看到以下响应:<\ n / p>

ID1 | ID2
4   | 2
4   | 4

4 个答案:

答案 0 :(得分:1)

尝试使用contrapositively这样做。

查找ID1 4的所有元素与查找 ID1 = 4的所有元素相同。

CREATE TABLE #temp (ID1 NVARCHAR(10), ID2 NVARCHAR(10))
INSERT INTO #temp(ID1,ID2) VALUES  (N'1',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'2',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'3',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'2')
INSERT INTO #temp(ID1,ID2) VALUES  (N'3',N'3')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'3')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'4')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'4')

SELECT * FROM #temp AS t

SELECT DISTINCT * FROM #temp AS t
WHERE id2 NOT IN (SELECT ID2 FROM #temp AS t WHERE ID1 <> 4)

答案 1 :(得分:1)

对于更一般的情况,这些查询可能对您有用(一般来说,我指的是当ID1不是4时):

select distinct t1.id1, t1.id2
from T as t1
where not exists (
    select 1
    from T as t2
    where t2.ID1 <> t1.ID1 and t2.ID2 = t1.ID2
)

select t1.id1, count(distinct t1.id2)
from T as t1
where not exists (
    select 1
    from T as t2
    where t2.ID1 <> t1.ID1 and t2.ID2 = t1.ID2
)
group by t1.id1

答案 2 :(得分:0)

你也可以这样做:

select 4,id2 from 
(select distinct ID1 , ID2 from t) t1
group by id2 
having count(*)=1

答案 3 :(得分:0)

有几种方法可以做到这一点:

SELECT t1.id1, t1.id2
  FROM mytable t1
 WHERE t1.id1 = 4
   AND NOT EXISTS ( SELECT 1 FROM mytable t2
                     WHERE t2.id2 = t1.id2
                       AND t2.id1 != 4 );

或:

SELECT id1, id2 FROM (
    SELECT id1, id2
      FROM mytable
     GROUP BY id1, id2
    HAVING COUNT(*) = 1
) WHERE id1 = 4;

或:

SELECT id1, id2 FROM (
    SELECT id1, id2, COUNT(*) OVER ( PARTITION BY id2 ) AS cnt
      FROM mytable
) WHERE id1 = 4
    AND cnt = 1;