这是表结构和示例数据
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
答案 0 :(得分:2)
有几种方法可以将数据从行转换为列。
如果您的数据库具有PIVOT
功能,那么您可以使用以下代码来转动数据:
select [Add], [Update], [Delete]
from
(
select id, name
from #tmp
) src
pivot
(
max(id)
for name in ([Add], [Update], [Delete])
) piv
或者您可以使用带有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
答案 1 :(得分:2)
请尝试:
SELECT [Add], [Update], [Delete]
FROM (select * from #tmp) up
PIVOT (sum(id) FOR Name IN ([Add], [Update], [Delete])) AS pvt