Лучший способ для трансформации - PullRequest
0 голосов
/ 23 сентября 2018

У меня есть что-то как

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 голосов
/ 24 сентября 2018

Большое предположение, что у вас есть только 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...