在Oracle中,获取另一个字段上一个字段的唯一出现次数

时间:2016-01-28 22:36:34

标签: oracle

我在Oracle数据库中有一个表格,如下所示:

ID1      ID2
 1        4
 1        4
 2        3
 1        5
 2        5
 3        6

基本上,我想写一个查询,它将计算ID1对ID1唯一的ID1,ID2对的数量。在上面的示例中,查询将返回:

ID1      countOfUniqueID2Pairs
 1                 1
 2                 1
 3                 1

这就是结果,因为每个ID1只有一个ID2,它是唯一的(1到4,2到3,3到6)。

有人知道怎么写这个查询吗?

2 个答案:

答案 0 :(得分:2)

Oracle安装程序

CREATE TABLE TABLE_NAME ( ID1, ID2 ) AS (
  SELECT 1, 4 FROM DUAL UNION ALL
  SELECT 1, 4 FROM DUAL UNION ALL
  SELECT 2, 3 FROM DUAL UNION ALL
  SELECT 1, 5 FROM DUAL UNION ALL
  SELECT 2, 5 FROM DUAL UNION ALL
  SELECT 3, 6 FROM DUAL
);

<强>查询

SELECT ID1,
       COUNT( DISTINCT ID2 )
FROM   TABLE_NAME
WHERE  ID2 IN ( SELECT ID2
                FROM   TABLE_NAME
                GROUP BY ID2
                HAVING   COUNT( DISTINCT ID1 ) = 1 )
GROUP BY ID1;

<强>结果:

       ID1 COUNT(DISTINCTID2)
---------- ------------------
         1                  1 
         2                  1 
         3                  1 

更新 - 查询2

SELECT ID1,
       COUNT( DISTINCT ID2 )
FROM   (
  SELECT ID1,
         ID2,
         COUNT( DISTINCT ID1 ) OVER ( PARTITION BY ID2 ) AS CNT1
  FROM   Table_Name
)
WHERE  CNT1 = 1
GROUP BY ID1;

答案 1 :(得分:0)

使用id2作为pivot的结果相同:

SELECT t2.id1
     , count(distinct t.id1) "countOfUniqueID2Pairs"
  FROM table_name t
    INNER JOIN table_name t2
      ON t2.id2 = t.id2
  GROUP BY t.id2, t2.id1
  HAVING count(distinct t.id1) = 1