将行转换为列

时间:2014-06-24 21:10:49

标签: sql-server-2008 tsql pivot

寻找将行更改为列的方法。 (comflag的类型为bit,而不是null)。帮助赞赏

Table1
Id    Commflag    value
122   0           Ce
125   1           Cf
122   0           Cg
125   1           cs

这是我想要的结果

id    ce    cf    cg    cs    cp
122   0     null  0     null  null
125   null  1     null  1     null

以下查询显示错误 -

 SELECT ID , [CE],[CF],[CG],[CS],[CP]
   FROM TABLE1
  PIVOT ((convert((Commflag)as varchar()) FOR value IN [CE],[CF],[CG],[CS],[CP] as pvt
  ORDER BY date

1 个答案:

答案 0 :(得分:1)

此查询可以执行您想要的操作:

select Id, pvt.Ce, pvt.Cf, pvt.CG, pvt.Cs, pvt.Cp
from 
(
 select Id, cast(Commflag as tinyint) Commflag, value
 from Table1
) t
pivot (max(Commflag) for value in ([Ce],[Cf],[CG],[Cs],[Cp])) pvt

SQL Fiddle

以下是另一种方法,不使用PIVOT

select Id,
max(case value when 'Ce' then CAST(Commflag as tinyint) else null end) Ce,
max(case value when 'Cf' then CAST(Commflag as tinyint) else null end) Cf,
max(case value when 'Cg' then CAST(Commflag as tinyint) else null end) Cg,
max(case value when 'Cs' then CAST(Commflag as tinyint) else null end) Cs,
max(case value when 'Cp' then CAST(Commflag as tinyint) else null end) Cp
from Table1
group by Id
order by Id

SQL Fiddle