日期:2014-05-17  浏览次数:20788 次

请教存储过程的编写
场景:
1 4105000000000180 11
2 4105000000000180 41
3 4105000000000180 31
4 4105000000000180 51
5 4105000000000181 42
6 4105000000000181 12
7 4105000000000181 11
8 4105000000000181 4
9 4105000000000188 45
10 4105000000000188 32
11 4105000000000188 21
12 4105000000000189 10

目标:
1 4105000000000180 11 41 31 51
5 4105000000000181 42 12 11 4
9 4105000000000188 45 32 21
12 4105000000000189 10

注:不是拼接,是行转列,数据很多,分组很多,所以需要用存储过程解决,
  11 41 31 51 '' ''
  42 12 11 4 '' ''
  45 32 21 '' '' ''
  10 '' '' '' '' ''
  这个最多六列,没有数据的为空
请高人帮忙解答,谢谢

------解决方案--------------------
ms不需要存储过程,用wm_concat函数就可以实现

create table t(id int, x int, y int);
insert into t values (1, 4105000000000180, 11);
insert into t values (2, 4105000000000180, 41);
insert into t values (3, 4105000000000180, 31);
insert into t values (4, 4105000000000180, 51);
insert into t values (5, 4105000000000181, 42);
insert into t values (6, 4105000000000181, 12);
insert into t values (7, 4105000000000181, 11);
insert into t values (8, 4105000000000181, 4);
insert into t values (9, 4105000000000188, 45);
insert into t values (10, 4105000000000188, 32);
insert into t values (11, 4105000000000188, 21);
insert into t values (12, 4105000000000189, 10);
commit;

select min(id), wm_concat(y) from t group by x;
------解决方案--------------------
select min(id), x, wm_concat(y) from t group by x;
------解决方案--------------------
40分归我了。
首先创建一个结果表,当然是用来装结果集。

第一步,先拼接,用WMSYS.WM_CONCAT函数。
第二步,更新,拼接后的字符后面再连接一个逗号
第三步,拆分---看例子:

---根据逗号拆分

CREATE OR REPLACE PROCEDURE Py_Rpt_Consume_Info AS
CURSOR My_Cursor IS
SELECT Id, NAME FROM p_k t;
Row_Set My_Cursor%ROWTYPE;
Str1 VARCHAR2(2000);
Str2 VARCHAR2(2000);
Str3 VARCHAR2(2000);
Str4 VARCHAR2(2000);
--Num1 NUMBER;
BEGIN
EXECUTE IMMEDIATE 'TRUNCATE TABLE p_kk';
FOR Row_Set IN My_Cursor LOOP
Str1 := Row_Set.NAME;
WHILE Instr(Str1, ',', 1) > 0 LOOP
Str2 := Substr(Str1, 1, Instr(Str1, ',', 1));
Str1 := Substr(Str1, Instr(Str1, ',', 1) + 1);
/* Str3 := Substr(Str2,
Instr(Str2, '(', 1) + 1,
Instr(Str2, ')', 1) - Instr(Str2, '(', 1) - 1);
Str4 := Substr(Str2, 1, Instr(Str2, '(', 1) - 1);*/
--NUM1 := TO_NUMBER(STR3);
/*-----
INSERT INTO TTTTT (STR1, STR2, STR3, STR4, NUM1)
SELECT STR1, STR2, STR3, STR4, NUM1 FROM DUAL;
COMMIT;
----- */
INSERT INTO p_Kk
(Id, NAME)
SELECT Row_Set.Id, Str2 FROM Dual;
COMMIT;
END LOOP;
  
END LOOP;
END Py_Rpt_Consume_Info;