我在oracle中有一个表,我想以矩阵形式转换它
表1:我有两种具有相应权重的用户
User_name M_User Total
user 1 user 2 7
user 1 user 3 19
user 1 user 7 5
user 3 user 2 1
user 2 user 7 1
最终结果应该是这样的:用户1 - >用户2的权重为7,因此该值出现在该单元格中,依此类推
user 1 user 2 user 3 user 7
user 1 0 7 19 5
user 3 0 1 0 0
user 2 0 0 0 1
user 7 0 0 0 0
我尝试了枢轴功能但是
SELECT *
FROM (SELECT USER_NAME, M_USER, TOTAL
FROM TEST)
PIVOT (MAX(TOTAL) FOR (M_USER) IN ('user 2' AS User2, 'user 3' AS User3 , 'user7' AS User7))
第一个问题是它显示'用户7'的空值而它不应该,第二个问题是我的文件中有很多数据(107k记录,包括重复),对于有限的数据,如上所述我可以使用'user 2'AS User2,'user 3'AS User3,'user7'AS User7在IN命令之后如果有这么大的数据怎么能写这行?当然我不能在IN之后写100k记录
我正在运行107k记录数据的脚本,我得到上面提到的错误,该代码适用于小数据集,但不适用于我的原始数据集
CREATE OR REPLACE FUNCTION GETUSERS RETURN SYS_REFCURSOR AS
QUERY CLOB;
RC SYS_REFCURSOR;
BEGIN
QUERY := 'SELECT USERS.USER_NAME ';
FOR TMP IN (SELECT DISTINCT UPPER(REPLACE(USER_NAME, ' ', '')) USER_NAME FROM (SELECT USER_NAME FROM TEST UNION ALL SELECT M_USER FROM TEST) ORDER BY USER_NAME)
LOOP
QUERY := QUERY || ' , MAX(COALESCE(TEST.' || TMP.USER_NAME || ' , 0)) ' || TMP.USER_NAME;
END LOOP;
QUERY := QUERY || ' FROM ( ';
QUERY := QUERY || ' SELECT DISTINCT USER_NAME ';
QUERY := QUERY || ' FROM ( ';
QUERY := QUERY || ' SELECT USER_NAME FROM TEST ';
QUERY := QUERY || ' UNION ALL ';
QUERY := QUERY || ' SELECT M_USER FROM TEST ';
QUERY := QUERY || ' ) ';
QUERY := QUERY || ' ) USERS ';
QUERY := QUERY || ' LEFT OUTER JOIN ( ';
QUERY := QUERY || ' SELECT USER_NAME';
FOR TMP IN (SELECT DISTINCT USER_NAME, REPLACE(USER_NAME, ' ', '') USER_COL_NM FROM (SELECT USER_NAME FROM TEST UNION ALL SELECT M_USER FROM TEST))
LOOP
QUERY := QUERY || ', CASE WHEN M_USER = ''' || TMP.USER_NAME
|| ''' THEN TOTAL ELSE 0 END AS ' || TMP.USER_COL_NM ;
END LOOP;
QUERY := QUERY || ' FROM TEST';
QUERY := QUERY || ' ) TEST ON USERS.USER_NAME = TEST.USER_NAME ';
QUERY := QUERY || 'GROUP BY USERS.USER_NAME ';
QUERY := QUERY || 'ORDER BY USERS.USER_NAME';
OPEN RC FOR QUERY;
RETURN RC;
END;
/
我得到的错误是
Error starting at line 2 in command:
EXEC :RC := GETUSERS;
Error report:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at "GETUSERS", line 10
ORA-06512: at line 1
06502. 00000 - "PL/SQL: numeric or value error%s"
*Cause:
*Action:
RC
------
我已经阅读了与此类似的其他问题,并且所有人都建议设置DBMS_OUTPUT.ENABLE(500000);
我试过但它给了我未知的命令错误,所以我手动将缓冲区大小设置为DBMS OUTPUT
中的无限制但是我我仍然得到错误,任何帮助?