Oracle中合并数据集(多行变一行),表A和表B之间为一对多的关系。
需求:
查询表A的全部数据,并将表A对应的表B数据的某个项目合并为一行,以[,]分隔。
ORACLE FUNCTION
CREATE OR REPLACE FUNCTION FUN_GETNAME (
ID IN NUMBER
) RETURN VARCHAR2
IS
RESULT_OUT VARCHAR2(20000);
BEGIN
DECLARE CURSOR C_CUR IS SELECT CTASKID FROM TABLE_B WHERE CID = ID ORDER BY CTASKID;
BEGIN
FOR ROWSTR IN C_CUR LOOP
RESULT_OUT := RESULT_OUT || ',' || ROWSTR.CTASKID;
END LOOP;
END;
RESULT_OUT := SUBSTR(RESULT_OUT, 2);
RETURN RESULT_OUT;
END;
/
查询数据的SQL:
SELECT A.ID, A.NAME, A.FLAG, A.DELETE_FLAG, FUN_GETNAME(A.CODE) AS SCH FROM TABLE_A A ORDER BY A.ID, SCH