如何将特定字段分成不同的列?

时间:2013-08-06 19:18:07

标签: sql oracle11g pivot plsqldeveloper

Oracle Database 11g企业版11.2.0.2.0版 - 64位生产。

我的表格格式如下:

No | User | Value
01 | Port | Funds   
01 | Vip1 | Systems  
02 | Port | Bank  
02 | Vip1 | Authority  

这就是我想要的:

No | Port  | Vip1
01 | Funds | Systems   
02 | Bank  | Authority  

现在的问题是,在此表中,除了Port和Vip1之外,User列还有6个其他条目。所以我想要6列及其各自的值。我还想要一个可以在具有不同用户列条目的其他类似表中使用的查询。这是我试图做的没有任何成功:

SELECT 
   No, 
   CASE user WHEN 'Port' THEN Value ELSE NULL END AS Port,  
   CASE user WHEN 'Vip1' THEN Value ELSE NULL END AS Vip1  
FROM table1

请让我知道你的想法。

1 个答案:

答案 0 :(得分:1)

你非常接近。你需要的是聚合:

SELECT 
   No, 
   max(CASE user WHEN 'Port' THEN Value END) AS Port,  
   max(CASE user WHEN 'Vip1' THEN Value END) AS Vip1  
FROM table1
group by No;

我也删除了else NULL。默认情况下,case语句在没有匹配时返回NULL

编辑:

实际上,在Oracle中,你可以做点什么。但是,您只有通用名称(除非您使用动态SQL):

select no,
       max(case when usernum = 1 then value end) as Val1,
       max(case when usernum = 2 then value end) as Val2,
       max(case when usernum = 3 then value end) as Val3,
       max(case when usernum = 4 then value end) as Val4,
       max(case when usernum = 5 then value end) as Val5,
       max(case when usernum = 6 then value end) as Val6,
       max(case when usernum = 1 then user end) as User1,
       max(case when usernum = 2 then user end) as User2,
       max(case when usernum = 3 then user end) as User3,
       max(case when usernum = 4 then user end) as User4,
       max(case when usernum = 5 then user end) as User5,
       max(case when usernum = 6 then user end) as User6
from (select t.*, dense_rank() over (order by user) as usernum
      from table1 t
     ) t
group by No;

这将返回带有值的6列和带有名称的6列。这可能不是您正在寻找的。但是,如果没有动态SQL,它可能是你能做到的最好的。