Sql server 更好的转型方式

Sql server 更好的转型方式,sql-server,tsql,Sql Server,Tsql,我有一些 通过运行脚本获得 declare @t table(id int identity, bucket varchar(200), startinventory int, nocontact int) INSERT INTO @t SELECT 'bucket1',1234,72500 UNION ALL SELECT 'bucket2',6784,60500 UNION ALL SELECT 'bucket3',678,52000 UNION ALL SELECT '

我有一些

通过运行脚本获得

declare @t table(id int identity, bucket varchar(200), startinventory int, nocontact int)

INSERT INTO @t  
SELECT 'bucket1',1234,72500 UNION ALL  
SELECT 'bucket2',6784,60500 UNION ALL  
SELECT 'bucket3',678,52000 UNION ALL  
SELECT 'bucket4',234,45000 

select * from @t 
正在查找其输出将为

执行转换的当前脚本如下所示

select 'startinventory'  as Activities,
    bucket1=(select startinventory from @t where id=1),
    bucket2=(select startinventory from @t where id=2), 
    bucket3=(select startinventory from @t where id=3),
    bucket4=(select startinventory from @t where id=4) union all
select 'nocontact', 
    (select nocontact from @t where id=1),
    (select nocontact from @t where id=2), 
    (select nocontact from @t where id=3),
    (select nocontact from @t where id=4)

有没有更好的方法来编写脚本?

一个很大的假设,即您只有一个固定的4个存储桶,但如果是这样,就可以了(提供了示例数据)


使用pivot的动态查询?
declare @bucket table(id int, bucket varchar(10), startinventory int, nocontact int)
insert @bucket values (1,'bucket1',1234,72500),(2,'bucket2',6784,60500),(3,'bucket3',678,52000),(4,'bucket4',234,45000)

select a as Activity,
    sum(case when id=1 then case when a='startinventory' then startinventory else NoContact end else 0 end) as bucket1,
    sum(case when id=2 then case when a='startinventory' then startinventory else NoContact end else 0 end) as bucket2,
    sum(case when id=3 then case when a='startinventory' then startinventory else NoContact end else 0 end) as bucket3,
    sum(case when id=4 then case when a='startinventory' then startinventory else NoContact end else 0 end) as bucket4
from (values ('startinventory'),('nocontact')) t(a)
cross join @bucket b
group by a