代码之家  ›  专栏  ›  技术社区  ›  priyanka.sarkar

更好的转型方式

  •  -1
  • priyanka.sarkar  · 技术社区  · 6 年前

    我有一些

    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 回复  |  直到 6 年前
        1
  •  1
  •   TomC    6 年前

    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