I
I
iscateli2022-03-03 23:47:26
Oracle
iscateli, 2022-03-03 23:47:26

How to set columns to transpose using SQL only?

How to turn rows into columns only using SQL (not PL / SQL), but I don’t need all the columns, but only certain ones, I can get the names of the columns themselves with a subquery, but in pivot, for example, you can’t use a subquery.

So here's what I found out myself, there are the following ways to get a pivot table:

Use subqueries directly in Select
Use DECODE or CASE Use the
PIVOT function

? No explicit column enumeration.

If this cannot be done, then maybe you can list all the columns, but how can you hide the null columns (all NULL values ​​are obtained in them)?

Miscellaneous examples from the list above:
subqueries in Select

SELECT
         object_type, systable.cnt "SYS", systemtable.cnt "SYSTEM", scotttable.cnt "SCOTT"
     FROM
         (SELECT object_type, COUNT(*) cnt from all_objects WHERE owner = 'SYS' GROUP BY object_type) systable
         FULL OUTER JOIN
         (SELECT object_type, COUNT(*) cnt from all_objects WHERE owner = 'SYSTEM' GROUP BY object_type) systemtable USING  (object_type)
         FULL OUTER JOIN
         (SELECT object_type, COUNT(*) cnt from all_objects WHERE owner = 'SCOTT' GROUP BY object_type) scotttable USING (object_type)
     WHERE object_type IN ('TABLE', 'VIEW', 'TRIGGER');

OBJECT_TYPE                 SYS     SYSTEM      SCOTT
-------------------- ---------- ---------- ----------
TRIGGER                      10          2 
TABLE                       998        157          
VIEW                       3865         12


DECODE or CASE
SELECT
         object_type,
         COUNT(DECODE(owner, 'SYS', 1, NULL)) "SYS",
         COUNT(DECODE(owner, 'SYSTEM', 1, NULL)) "SYSTEM",
         COUNT(DECODE(owner, 'SCOTT', 1, NULL)) "SCOTT"
     FROM all_objects
     WHERE object_type IN ('TABLE', 'VIEW', 'TRIGGER')
     GROUP BY object_type;

OBJECT_TYPE                 SYS     SYSTEM      SCOTT
-------------------- ---------- ---------- ----------
TRIGGER                      10          2          0
TABLE                       998        157          0
VIEW                       3865         12          0


PIVOT function
SELECT *
     FROM (
         SELECT owner, object_type
         FROM all_objects
         WHERE object_type IN ('TABLE', 'VIEW', 'TRIGGER'))
     PIVOT (COUNT(*) FOR owner IN ('SYS', 'SYSTEM', 'SCOTT'));

OBJECT_TYPE               'SYS'   'SYSTEM'    'SCOTT'
-------------------- ---------- ---------- ----------
TRIGGER                      10          2          0
TABLE                       998        157          0
VIEW                       3865         12          0

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question