0

这是表结构和示例数据

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
4

2 回答 2

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

于 2013-03-22T11:06:01.783 回答
2

请试试:

SELECT [Add], [Update], [Delete]
    FROM (select * from #tmp) up 
        PIVOT (sum(id) FOR Name IN ([Add], [Update], [Delete])) AS pvt
于 2013-03-22T11:06:18.723 回答