如何选择具有不同值的唯一且重复的行

时间:2018-01-10 10:18:47

标签: sql oracle group-by aggregate-functions having

如何在Oracle中按预期获取此表。我尝试这样做,如下面选择,但它没有给我正确的结果。我期望的是仅获取唯一的并且如果这些是不同值的记录则排除。对不起,如果之前被问过,但我找不到它。

SELECT * 
FROM ...
WHERE number IN ( SELECT name
                  FROM (SELECT *
                        FROM table
                        WHERE number IN ('Mel','Jose','Kim')
                  ) ds
                  GROUP BY number
                  HAVING COUNT (*) = 1)

目前的结果:

 number name
   aaa   Mel
   asd   Jose
   fsa   Jose
   xdf   Jose
   zzz   Kim
   zzz   Kim

预期结果:

aaa Mel
zzz Kim

2 个答案:

答案 0 :(得分:4)

你很接近 - 我认为你只是错过了你的条款中的不同点。

E.g:

WITH your_table AS (SELECT 100 nmbr, 'Mel' NAME FROM dual UNION ALL
                    SELECT 112 nmbr, 'Jose' NAME FROM dual UNION ALL
                    SELECT 212 nmbr, 'Jose' NAME FROM dual UNION ALL
                    SELECT 313 nmbr, 'Jose' NAME FROM dual UNION ALL
                    SELECT 101 nmbr, 'Kim' NAME FROM dual UNION ALL
                    SELECT 101 nmbr, 'Kim' NAME FROM dual)
-- end of mimicking data in your table
-- you already have this table, so you would just need the below sql:
SELECT min(nmbr) nmbr,
       NAME
FROM   your_table
GROUP BY NAME
HAVING COUNT(DISTINCT nmbr) = 1;

      NMBR NAME
---------- ----
       101 Kim
       100 Mel

只是为了证明nmbr列是否为NUMBER或VARCHAR2数据类型无关紧要:

WITH your_table AS (SELECT 'aaa' nmbr, 'Mel' NAME FROM dual UNION ALL
                    SELECT 'asd' nmbr, 'Jose' NAME FROM dual UNION ALL
                    SELECT 'fsa' nmbr, 'Jose' NAME FROM dual UNION ALL
                    SELECT 'xfd' nmbr, 'Jose' NAME FROM dual UNION ALL
                    SELECT 'zzz' nmbr, 'Kim' NAME FROM dual UNION ALL
                    SELECT 'zzz' nmbr, 'Kim' NAME FROM dual)
-- end of mimicking data in your table
-- you already have this table, so you would just need the below sql:
SELECT min(nmbr) nmbr,
       NAME
FROM   your_table
GROUP BY NAME
HAVING COUNT(DISTINCT nmbr) = 1;

NMBR NAME
---- ----
zzz  Kim
aaa  Mel

答案 1 :(得分:2)

您可以nested sql the inner part消除与id& name,并在the outer part中删除仅包含name的重复内容,如下所示:

SELECT MAX(id),name 
FROM (SELECT id,name FROM mytable GROUP BY id, name)  
GROUP BY name 
HAVING COUNT(1) = 1
ORDER BY MAX(id);

<强>输出:

ID       NAME
-----    ------
100      Mel
101      Kim

D e m o 1

  

完全相同的sql适用于您的第二种情况:

     

D e m o 2