如何使用pivot子句?

时间:2017-06-21 19:59:07

标签: sql oracle pivot

如何从右边的表格左侧转换表格?我使用了pivot子句但是没有用。这就是我试过的:

select *
from   (
  select categ, name from students
)
pivot (count(books) for name in('Tom', 'Jane')); 

enter image description here

2 个答案:

答案 0 :(得分:0)

Oracle安装程序

CREATE TABLE students ( categ, name, books ) AS
  SELECT 1, 'Jane', 2 FROM DUAL UNION ALL
  SELECT 1, 'Tom',  3 FROM DUAL UNION ALL
  SELECT 2, 'Jane', 4 FROM DUAL UNION ALL
  SELECT 3, 'Jane', 0 FROM DUAL UNION ALL
  SELECT 3, 'Tom',  1 FROM DUAL;

<强>查询

select Categ, jane, tom
from   ( select categ, name, books from students )
pivot ( MAX(books) for name in ('Tom' AS tom, 'Jane' AS jane)); 

<强>输出

     CATEG       JANE        TOM
---------- ---------- ----------
         1          2          3
         2          4           
         3          0          1

答案 1 :(得分:-1)

我昨天创建的一个例子是:

假设你有一个像这样的表:

姓名薪水
马克3000
大卫4000
Kyal 15000
Jhon 10000

然后下面的查询可以生成如下所示的结果:

SELECT [Mark], [David], [Kyal], [Jhon] 
FROM 
( SELECT Name, Salary 
FROM EmpSalary ) AS MainTable 
PIVOT 
( 
SUM(Salary) 
FOR Name IN ([Mark], [David], [Kyal], [Jhon]) 
) AS PT; 

Output: 

Mark   David   Kyal   Jhon 
3000   4000   15000   10000

希望这是你想要达到的目标。

的Manoj。