将行转换为列

时间:2013-12-02 12:27:01

标签: sql sql-server-2008

我想将行转换为列,这是我的表

Id Total
1  50
2  50
3  150

基本上我想要这个输出

ID 50
1  1
2  1
3  (null)

到目前为止我尝试过的是

select *
from 
(
  select id, total
  from <table>
) src
pivot
(
  //Here is where i'm stuck...what should i write here
) 

1 个答案:

答案 0 :(得分:3)

您好找到以下解决方案

停止临时表

select 1 as id,50 as total into #temp
union all

select 2 as id,50 as total
Union all
select 3 as id,150 as total

准备列     声明@columns varchar(Max)

SELECT  @columns= COALESCE(@columns+',[','[')+cast( total as Varchar(max))+']' FROM     (select DISTINCT total from #temp) as xx

print @columns

执行查询

EXEC ('
select *
from 
(
  select id as idd,id, total
  from #temp
) src
pivot
(
  COUNT(id) FOR total IN('+@columns+')
) as PVT
')

DROP TABLE #temp 

您可以使用动态

生成任意数量的列