如何为非数字列制作数据透视表

时间:2019-03-29 17:22:39

标签: sql-server pivot

我正在尝试提取与表中文件名相关联的PO编号的记录。一个文件名最多可以有五个PO号。 该表如下所示:

ID  Filename             PO#          
-----------------------------------
1   file1                 001      
2   file1                 002         
3   file1                 003        
4   file1                 004    
5   file2                 001
6   file2                 002   
7   file3                 001 
.
.
.

我想要的是:

Filename             PO#1    PO#2   PO#3   PO#4   PO#5          
-----------------------------------------------------------  
file1                001     002     003    004
file2                001     002  
file2                001       

我尝试了Pivot。

这是我的代码:

    SELECT [1] AS PO1, [2] AS PO2, [3] AS PO3, [4] AS PO4,[5] AS PO5
    From 
    (SELECT ROW_NUMBER() OVER(PARTITION BY filename ORDER BY [ID] 
    ASC) AS Row#, *
    FROM 1) as t
    PIVOT (
    max(PO)
    FOR Row#ByFileName IN ([1],[2], [3],[4],[5])) AS PivotTable

但是,结果是

Filename             PO#1    PO#2   PO#3   PO#4   PO#5          
-----------------------------------------------------------  
file1                  001
file1                 null    002   null   null   null
file1                 null    null   003   null   null        
file1                 null    null  null    004   null   
file2                  001
file2                 null    002   null   null   null       
file3                  001
.
.

我还尝试使用东西和xml路径将多行合并为一行,并使用子字符串将一列拆分为多列。但是我无法得到我所拥有的。

任何想法都将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:0)

您可以改为进行条件聚合:

select filename,
       max(case when seq = 1 then po end) as [PO#1],
       . . . 
       max(case when seq = 5 then po end) as [PO#5]
from (select t.*,
             row_number() over (partition by filename order by id) as seq
      from table t
     ) t
group by filename;