如何在Oracle中执行以下操作:
我有一张(简化的)表格:
+-----+-----+-----+
| a | b | ... |
+-----+-----+-----+
| 1 | 7 | ... |
| 2 | 5 | ... |
| 1 | 7 | ... |
+-----+-----+-----+
a
作为一个人的唯一标识符,b
是我感兴趣的跨行匹配的字段。我如何构建一个基本上说"给我个人ID的查询,其中该人有多个b
值(即重复)"?
到目前为止,我已经尝试过:
SELECT a FROM mytable GROUP BY a HAVING COUNT(DISTINCT b) > 1;
这感觉很接近,除了它只是给了我用户ID,其中用户有多个唯一 b
,我怀疑它来自DISTINCT
部分,但我不确定如何更改查询以实现我想要的。
答案 0 :(得分:1)
尝试
group by a,b having count(b) > 1
您的7,5,7
计为2(一7
,一5
)。这一个将计算任何分组中的总B数,因此您将获得1,7
- > 2
和1,5
- > 1
答案 1 :(得分:1)
Oracle 11g R2架构设置:
CREATE TABLE mytable ( a, b ) AS
SELECT LEVEL, LEVEL FROM DUAL CONNECT BY LEVEL <= 2000
UNION ALL
SELECT LEVEL *2, LEVEL * 2 FROM DUAL CONNECT BY LEVEL <= 1000;
查询1 :
WITH data AS (
SELECT a
FROM mytable
GROUP BY a
HAVING COUNT(b) > COUNT( DISTINCT b )
ORDER BY a
),
numbered AS (
SELECT a,
ROWNUM AS rn
FROM data
)
SELECT a
FROM numbered
WHERE rn <= 20
<强> Results 强>:
| A |
|----|
| 2 |
| 4 |
| 6 |
| 8 |
| 10 |
| 12 |
| 14 |
| 16 |
| 18 |
| 20 |
| 22 |
| 24 |
| 26 |
| 28 |
| 30 |
| 32 |
| 34 |
| 36 |
| 38 |
| 40 |