Oracle在组的列中查找具有多个值的行

zlhcx6iw  于 2023-10-16  发布在  Oracle
关注(0)|答案(2)|浏览(114)

我试图找到是否有多个运营商的一个部分号码(组)。我尝试了下面的代码,但不工作。

SELECT PART_NO,CARRIER,
       ROW_NUMBER() OVER (PARTITION BY PART_NO,CARRIER ORDER BY PART_NO,CARRIER)
FROM CARR_NM;

数据看起来像这样:

PART_NO       CARRIER
1A3271         DHL
1A3271         MAERSK
1B0056         ALEXIM

我想挑选的部分编号1A 3271有多个承运人DHL和马士基。任何帮助都非常感谢!

6qfn3psc

6qfn3psc1#

PART_NO聚合,然后Assert载波的非重复计数大于1:

SELECT PART_NO
FROM CARR_NM
GROUP BY PART_NO
HAVING COUNT(DISTINCT CARRIER) > 1;

如果你想要所有匹配PART_NO的完整记录,那么你可以把上面的内容放到CTE中并重用它:

WITH cte AS (
    SELECT PART_NO
    FROM CARR_NM
    GROUP BY PART_NO
    HAVING COUNT(DISTINCT CARRIER) > 1
)

SELECT *
FROM CARR_NM
WHERE PART_NO IN (SELECT PART_NO FROM cte);
vqlkdk9b

vqlkdk9b2#

使用COUNT解析函数,而不是ROW_NUMBER

SELECT part_no,
       carrier
FROM   (
  SELECT part_no,
         carrier,
         COUNT(DISTINCT carrier) OVER (PARTITION BY part_no) AS num_carriers
  FROM   carr_nm
)
WHERE  num_carriers > 1;

最外层的查询是一个内联视图,它只从内部查询中过滤数据,因此它只从表中读取一次。

相关问题