用于将当前行值与先前行值合并的SQL查询

时间:2017-11-01 11:29:43

标签: sql oracle oracle11g

我有以下格式的源数据。

RN  ID  NAME
1   1   P
2   2   Q
3   3   R
4   4   S
5   5   T
6   1   A
7   2   B
8   3   C
9   4   D
10  5   E

我需要关注输出。

RN  ID  NAME
1   1   P
2   2   PQ
3   3   PQR
4   4   PQRS
5   5   PQRST
6   1   A
7   2   AB
8   3   ABC
9   4   ABCD
10  5   ABCDE

请为此提供SQL查询。

1 个答案:

答案 0 :(得分:3)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name ( RN, ID, NAME ) As
SELECT  1, 1,   'P' FROM DUAL UNION ALL
SELECT  2, 2,   'Q' FROM DUAL UNION ALL
SELECT  3, 3,   'R' FROM DUAL UNION ALL
SELECT  4, 4,   'S' FROM DUAL UNION ALL
SELECT  5, 5,   'T' FROM DUAL UNION ALL
SELECT  6, 1,   'A' FROM DUAL UNION ALL
SELECT  7, 2,   'B' FROM DUAL UNION ALL
SELECT  8, 3,   'C' FROM DUAL UNION ALL
SELECT  9, 4,   'D' FROM DUAL UNION ALL
SELECT 10, 5,   'E' FROM DUAL

查询1

SELECT RN,
       ID,
       REPLACE( SYS_CONNECT_BY_PATH( NAME, ',' ), ',' ) AS NAME
FROM   TABLE_NAME
START WITH ID = 1
CONNECT BY PRIOR ID + 1 = ID
AND        PRIOR ASCII(NAME) + 1 = ASCII(NAME)

<强> Results

| RN | ID |  NAME |
|----|----|-------|
|  1 |  1 |     P |
|  2 |  2 |    PQ |
|  3 |  3 |   PQR |
|  4 |  4 |  PQRS |
|  5 |  5 | PQRST |
|  6 |  1 |     A |
|  7 |  2 |    AB |
|  8 |  3 |   ABC |
|  9 |  4 |  ABCD |
| 10 |  5 | ABCDE |

查询2

SELECT RN,
       ID,
       REPLACE( SYS_CONNECT_BY_PATH( NAME, ',' ), ',' ) AS NAME
FROM   TABLE_NAME
START WITH ID = 1
CONNECT BY PRIOR ID + 1 = ID
AND        PRIOR RN + 1 = RN

<强> Results

| RN | ID |  NAME |
|----|----|-------|
|  1 |  1 |     P |
|  2 |  2 |    PQ |
|  3 |  3 |   PQR |
|  4 |  4 |  PQRS |
|  5 |  5 | PQRST |
|  6 |  1 |     A |
|  7 |  2 |    AB |
|  8 |  3 |   ABC |
|  9 |  4 |  ABCD |
| 10 |  5 | ABCDE |