SQL:如何在SQL中将行转换为列

时间:2013-03-22 11:02:33

标签: sql sql-server tsql pivot

这是表结构和示例数据

create table #tmp ( Id int, Name varchar(100))
insert into #tmp (Id,Name)
Values (1,'Add')
insert into #tmp (Id,Name)
Values (2,'Update')

insert into #tmp (Id,Name)
Values (3,'Delete')

和预期结果应该是。

Add  Update  Delete
===  ======  ======
1    2       3

2 个答案:

答案 0 :(得分:2)

有几种方法可以将数据从行转换为列。

如果您的数据库具有PIVOT功能,那么您可以使用以下代码来转动数据:

select [Add], [Update], [Delete]
from
(
  select id, name
  from #tmp
) src
pivot
(
  max(id)
  for name in ([Add], [Update], [Delete])
) piv

请参阅SQL Fiddle with Demo

或者您可以使用带有CASE表达式的聚合函数:

select 
  max(case when name = 'Add' then id end) [Add],
  max(case when name = 'Update' then id end) [Update],
  max(case when name = 'Delete' then id end) [Delete]
from #tmp

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

请尝试:

SELECT [Add], [Update], [Delete]
    FROM (select * from #tmp) up 
        PIVOT (sum(id) FOR Name IN ([Add], [Update], [Delete])) AS pvt