Oracle为给定列选择具有相同值的两个(或更多)相邻行

时间:2014-01-15 21:31:36

标签: oracle

如何在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部分,但我不确定如何更改查询以实现我想要的。

2 个答案:

答案 0 :(得分:1)

尝试

group by a,b having count(b) > 1

您的7,5,7计为2(一7,一5)。这一个将计算任何分组中的总B数,因此您将获得1,7 - > 21,5 - > 1

答案 1 :(得分:1)

SQL Fiddle

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 |