Count DISTINCT可在列表中查找具有不同值的记录

xuo3flqw  于 2022-09-18  发布在  Java
关注(0)|答案(2)|浏览(132)

我有一个简单的问题:如何在SQL(准确地说是Oracle)中使用HAVING COUNT(DISTINCT)来仅返回其中有2列具有相同记录但1列具有不同记录的行。

示例

CA_ID   BA_ID   SA_ID       
----    -----   --------    
CA1     BA1     SA1 
CA1     BA2     SA1 
CA1     BA2     SA2
CA1     BA3     SA1 
CA2     BA4     SA3
CA2     BA4     SA4
CA2     BA5     SA4
CA3     BA6     SA6

在该示例中,我想创建一个显示1个相同的CA_ID和SA_ID,但具有不同的BA_ID的查询。

CA_ID   BA_ID   SA_ID       
----    -----   --------    
CA1     BA1     SA1 
CA1     BA2     SA1 
CA1     BA3     SA1 
CA2     BA4     SA4
CA2     BA5     SA4
mwg9r5ms

mwg9r5ms1#

select  CA_ID   
       ,BA_ID   
       ,SA_ID
from   (select  t.*
               ,count(distinct BA_ID)  over(partition by CA_ID, SA_ID) as dcount
        from    t
       ) t
where  dcount > 1

CA_ID|BA_ID|SA_ID
-|-|
CA1|BA1|SA1
CA1|BA2|SA1
CA1|BA3|SA1
CA2|BA4|SA4
CA2|BA5|SA4

Fiddle

fcy6dtqo

fcy6dtqo2#

我们可以尝试使用聚合方法来查找匹配的CA_IDSA_ID值:

WITH cte AS (
    SELECT CA_ID, SA_ID
    FROM yourTable
    GROUP BY CA_ID, SA_ID
    HAVING MIN(BA_ID) <> MAX(BA_ID)
)

SELECT t1.*
FROM yourTable t1
WHERE EXISTS (
    SELECT 1
    FROM cte t2
    WHERE t2.CA_ID = t1.CA_ID AND
          t2.SA_ID = t1.SA_ID
);

相关问题