The simple answer is: no, you cannot.
In Oracle, it is possible to do a dynamic pivot on an unknown number of columns but it is not something that you can do using a simple SELECT * FROM student
. You will need to use PL/SQL to build some dynamic SQL:
VARIABLE cur REFCURSOR;
DECLARE
p_sql CLOB;
BEGIN
SELECT 'SELECT ''ROLL_NO'' AS "NAME", '
|| LISTAGG(
'MAX( CASE name WHEN '''
|| name
|| ''' THEN roll_no END ) AS "'
|| name || '"',
','
) WITHIN GROUP ( ORDER BY ROWNUM )
|| ' FROM students'
INTO p_sql
FROM students;
OPEN :cur FOR p_sql;
END;
/
PRINT cur;
Output:
NAME gokul gokul1
------- ----------- -----------
ROLL_NO 3 34
Edit
The above code will work where the LISTAGG
output is under 4000 bytes but if you want to go over that then you need a slightly different method:
VARIABLE cur REFCURSOR;
DECLARE
TYPE name_t IS TABLE OF students.name%type;
p_sql CLOB;
names name_t;
BEGIN
SELECT DISTINCT name
BULK COLLECT INTO names
FROM students;
p_sql := EMPTY_CLOB() || 'SELECT ''ROLL_NO'' AS "NAME"';
FOR i IN 1 .. names.COUNT LOOP
p_sql := p_sql || ', MAX( CASE name WHEN '''
|| names(i)
|| ''' THEN roll_no END ) AS "'
|| names(i)
|| '"';
END LOOP;
p_sql := p_sql || ' FROM students';
OPEN :cur FOR p_sql;
END;
/
PRINT cur;