原始表:
1.列转行就是将一列的数据变成行显示,列转行使用了sum聚合函数,case when判断,列转行需要自己定义别名。
列转行语句:
SELECT SUM(CASE
WHEN T.LOC = ‘NEW YORK‘ THEN
T.DEPTNO
END) AS COLUMN_00001,
SUM(CASE
WHEN T.LOC = ‘DALLAS‘ THEN
T.DEPTNO
END) AS COLUMN_00002,
SUM(CASE
WHEN T.LOC = ‘CHICAGO‘ THEN
T.DEPTNO
END) AS COLUMN_00003,
SUM(CASE
WHEN T.LOC = ‘BOSTON‘ THEN
T.DEPTNO
END) AS COLUMN_00004
FROM DEPT T; --列转行
显示的结果:
2.行转列就是将一行变成一列显示,行转列使用了sum聚合函数,case when判断,别名要和每行中的每一列的值一样。
行转列代码:
SELECT SUM(CASE
WHEN T.LOC = ‘NEW YORK‘ THEN
T.DEPTNO
END) AS NEWYORK,
SUM(CASE
WHEN T.LOC = ‘DALLAS‘ THEN
T.DEPTNO
END) AS DALLAS,
SUM(CASE
WHEN T.LOC=‘CHICAGO‘ THEN
T.DEPTNO
END) AS CHICAGO,
sum(CASE
WHEN T.LOC=‘BOSTON‘ THEN
T.DEPTNO
END) AS BOSTON
FROM DEPT T;
显示结果: