pivot function and unpivot

A: UNPIVOT column switch function
example demonstrates:
create a table tmp_test, data as shown in FIG
pivot function and unpivot
code shows:
SELECT code, name, cource, Grade from tmp_test
UNPIVOT (
Grade Source for in (chinese, Math, Dictionary Dictionary English)
);
the data results display:
pivot function and unpivot

Two: pivot row transfer column function
example demonstrates:
create a table tmp_test2, data as shown in FIG
pivot function and unpivot
code shows:
SELECT *
from (SELECT username, Subject, Source from tmp_test2)
Pivot (SUM (Source)
for Subject in ( 'language' language, 'mathematics' math, 'English' in English));
data results show:
pivot function and unpivot
in fact, the sql can also use decode function to achieve:
the SELECT username,
SUM (decode (Subject, 'language', source, 0)) language,
SUM ( decode (subject, 'mathematics', source, 0)) Mathematics,
SUM (decode (subject, 'English', source, 0)) in English,
from tmp_test2
Group by username;

Summary:
Pivot function: turn the row column function:
  Syntax: (value to be either a train where the aggregate function for a column name in (name of the column to be converted value)) Pivot;
UNPIVOT function: Column switch function:
  Syntax: unpivot (New where the value of the column where the column name for the new additional columns into rows after the column name in (column names to be converted to lines));
the implementation of the principle: the pivot function or unpivot function connected to the back of the query result set. Process corresponds to the result set.

Today first here, as dynamic row turn in the next column we discussed!

Guess you like

Origin blog.51cto.com/12777507/2404262