问题
Initial table students
NAME School Class
John Hs English
Steve Hs Maths
Matthew Hs Science
Jim Hs History
Output Needed: I need the query to auto pick up Name column data from initial table and change it to column headers in output and since the names will continuously change i cannot hard code the names using simple pivot query. I am new to pivot queries so I wanted to request if someone can help me out. Thank You.
School John Steve Matthew Jim
Hs English Maths Science History
Here's what i tried: *Note( I am trying to use this query in Oracle Sql Developer to achieve the output format)
declare
sqlqry clob;
cols clob;
begin
select listagg('''' || NAME || ''' as "' || NAME || '"', ',') within group (order by NAME)
into cols
from (select distinct NAME from Students);
sqlqry :=
'
select * from(select NAME,SCHOOL,CLASS from Students)
pivot(MAX(CLASS) FOR NAME IN (' || cols || ')
)';
execute immediate sqlqry;
end;
回答1:
You're on the right track but that case fails when more than one class defined for at least one student. A ROW_NUMBER()
analytic function within resolves the issue. So, create a stored function including SYS_REFCURSOR
:
CREATE OR REPLACE FUNCTION get_student_rs RETURN SYS_REFCURSOR IS
recordset SYS_REFCURSOR;
sqlqry VARCHAR2(32767);
cols VARCHAR2(32767);
BEGIN
SELECT LISTAGG(''''||name||''' AS "'||name||'"' ,',') WITHIN GROUP (ORDER BY 0)
INTO cols
FROM ( SELECT DISTINCT name FROM Students );
sqlqry :=
'SELECT *
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY 0) AS rn,
s.*
FROM Students s
)
PIVOT (
MAX(class) FOR name IN ('||cols||')
)
ORDER BY rn';
OPEN recordset FOR sqlqry;
RETURN recordset;
END;
/
Assume there's one more record inserted ;
Name School Class
---- ------ -------
Jim Hs History
then invoke
VAR rc REFCURSOR
EXEC :rc := get_student_rs;
PRINT rc
from SQL Developer's Command Line in order to see the result set which will be :
RN SCHOOL Jim John Matthew Steve
-- ------ ------- ------- ------- ------
1 Hs Maths English Science Maths
2 Hs History
来源:https://stackoverflow.com/questions/63694461/dynamic-pivot-query-using-sql-developer-oracle