更好的转型方式

时间:2018-09-23 17:20:08

标签: sql-server tsql

我有东西

enter image description here

通过运行脚本获得

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 

寻找将输出为

的转换

enter image description here

下面是进行转换的当前脚本

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)

是否有更好的脚本编写方法?

1 个答案:

答案 0 :(得分:1)

一个大的假设是您只有4个固定的存储桶,但如果这样做,它将做到这一点(提供示例数据)。

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