varchar数据类型返回null的SQL PIVOT

时间:2018-07-04 15:00:42

标签: sql sql-server pivot

我正在尝试透视sql表中的数据,以便每个记录ID仅获得一行。但是,我正在运行的代码不断返回空值作为最终结果。

我的桌子如下:

"Sequence"  "University Issuing Body"**    
"1" "College1"    
"1" "College2"
"2" "College1"    
"2" "College1"    
"2" "College2"

我需要表格如下所示:

"Sequence"  "University Issuing Body1"  "University Issuing Body2"  "University Issuing Body3"    
"1" "College1"  "College2"  "NULL"
"2" "College1"  "College1"  "College2"

我正在运行的代码如下:

select
     Sequence]
    ,[University Issuing Body_1]
    ,[University Issuing Body_2]
    ,[University Issuing Body_3]

from (
    select
         [Sequence]
        ,[University Issuing Body]
        ,'University Issuing Body' + cast(row_number() over(partition by [Sequence] order by [University Issuing Body]) as varchar(12)) as hdg
    from [AB_DCU_IP_2018].[dbo].[PR_Q_Joined]
    ) d
    pivot(
        max([University Issuing Body])
        for hdg in ([University Issuing Body_1], [University Issuing Body_2], [University Issuing Body_3])
        )pvt

但是,当我运行上面的代码时,我所有的值都显示为空,并且得到以下结果:

"Sequence"  "University Issuing Body_1" "University Issuing Body_2" "University Issuing Body_3"

"1" "NULL"  "NULL"  "NULL"

"2" "NULL"  "NULL"  "NULL"

任何帮助将不胜感激,因为我一直在在线寻找解决方案,而且似乎找不到我要去哪里。

谢谢。

2 个答案:

答案 0 :(得分:1)

只需使用条件聚合:

select Sequence,
       max(case when seqnum = 1 then [University Issuing Body] end) as University_Issuing_Body_1,
       max(case when seqnum = 2 then [University Issuing Body] end) as University_Issuing_Body_2,
       max(case when seqnum = 3 then [University Issuing Body] end) as University_Issuing_Body_3
from (select pqj.*
             row_number() over (partition by [Sequence] order by [University Issuing Body]) as seqnum
      from [AB_DCU_IP_2018].[dbo].[PR_Q_Joined] pqj
     ) d
group by [University Issuing Body];

如果您确实要使用pivot,则无需定义hdg

select [Sequence],
       [1] as [University Issuing Body_1], 
       [2] as [University Issuing Body_2], 
       [3] as [University Issuing Body_3]
from (select [Sequence], [University Issuing ,Body]
             row_number() over (partition by [Sequence] order by [University Issuing Body]) as seqnum
      from [AB_DCU_IP_2018].[dbo].[PR_Q_Joined]
     ) d
pivot (max([University Issuing Body])
       for seqnum in (1, 2, 3)
      )pvt

答案 1 :(得分:1)

您正在使用hdg构造中间表,格式为University Issuing Body<n>。但是,随后您将提取hdg格式为University Issuing Body_<n>的值。毫不奇怪,这与任何内容都不匹配-因此您会得到NULL。

只需在您的hdg构造中加一个下划线:

select
 [Sequence]
,[University Issuing Body_1]
,[University Issuing Body_2]
,[University Issuing Body_3]
from (
    select
        [Sequence]
        ,[University Issuing Body]
        ,'University Issuing Body_' + cast(row_number() over(partition by [Sequence] order by [University Issuing Body]) as varchar(12)) as hdg
    from [AB_DCU_IP_2018].[dbo].[PR_Q_Joined]
    ) d
    pivot(
        max([University Issuing Body])
        for hdg in ([University Issuing Body_1], [University Issuing Body_2], [University Issuing Body_3])
        ) pvt