ORACLE 一行转多行
/**解决方法的核心是:产生出1-10的一个列,作为“辅助列”**/
SELECT LEVEL l FROM dual CONNECT BY LEVEL<=10;
【问题】
两个表 A B
A 表:
id pid
A1 1
A2 2
A3 3
B 表:
pid pnumber
1 2
2 3
3 5
要根据Pnumber的数量生成这样的资料
id list
A1 A1-1
A1 A1-2
A2 A1-1
A2 A1-2
A2 A1-3
A3 A1-1
A3 A1-2
A3 A1-3
A3 A1-4
A3 A1-5
/**创建测试的表T1 也就是楼主说的A表**/
CREATE TABLE t1(
ID VARCHAR2(10),
pid VARCHAR2(10)
);
/**创建测试的表T2 也就是楼主说的B表**/
CREATE TABLE t2(
pid VARCHAR2(10),
pnumber VARCHAR2(10)
);
/**插入T1的数据,插入T2的测试数据**/
INSERT INTO t1 VALUES('A1','1');
INSERT INTO t1 VALUES('A2','2');
INSERT INTO t1 VALUES('A3','3');
INSERT INTO t2 VALUES('1','2');
INSERT INTO t2 VALUES('2','3');
INSERT INTO t2 VALUES('3','5');
/**解决方法的核心是:产生出1-10的一个列,作为“辅助列”**/
SELECT LEVEL l FROM dual CONNECT BY LEVEL<=10;
/**最终的SQL**/
SELECT T1.ID, 'A1-'||T3.DZ AS LIST
FROM T1, T2, (SELECT LEVEL DZ FROM DUAL CONNECT BY LEVEL <= 10) T3
WHERE T1.PID = T2.PID
AND T3.DZ <= T2.PNUMBER
ORDER BY 1,2;