我不相信,你可以建立一个SQL这样做,因为你有一个可变数目或列。我能找到的最好的是一些动态的SQL建立查询:
set serveroutput on
DECLARE
vSQL VARCHAR2(1000) :=
'SELECT *
FROM (SELECT paper_code, inst_node
FROM test)
PIVOT (count(1) FOR (paper_code) IN (PaperCodeList))
order by inst_node';
vPaperCodeList VARCHAR2(1000);
BEGIN
SELECT LISTAGG(paper_code || ' as "' || paper_code ||'"', ', ') WITHIN GROUP (ORDER BY paper_code) as list
INTO vPaperCodeList
FROM (SELECT DISTINCT paper_code FROM test);
vSQL := REPLACE(
vSQL,
'PaperCodeList',
vPaperCodeList
);
dbms_output.put_line(vSQL);
END;
/
这将建立一个像查询以下内容:
SQL> SELECT *
2 FROM (SELECT paper_code, inst_node
3 FROM test)
4 PIVOT (count(1) FOR (paper_code) IN (71 as "71", 72 as "72", 73 as "73", 75 as "75"))
5 order by inst_node;
INST_NODE 71 72 73 75
---------- ---------- ---------- ---------- ----------
10 2 1 2 1
11 1 1 2 0