两列上的MSSQL Pivot

时间:2017-07-12 20:58:14

标签: sql-server

嘿所以我试图转动两列,如果你看到我的代码,我可以在一列上执行我的支点。有没有办法将我的ReturnedItems列转移到ShippedItems旁边?

谢谢

declare @t table (
store varchar(20),
ShippedItems int,
ReturnedItems int
)

insert into @t
values ('Walmart',1,2)
insert into @t
values ('Lowes',1,2)
insert into @t
values ('Home Depot',1,2)

select * from (
select * from @t
) pivottable
pivot
(
sum(ShippedItems)
for store in (Walmart,Lowes,[Home Depot])
) x

1 个答案:

答案 0 :(得分:1)

这是你要找的吗?

SELECT 
    Walmart_ShippedItems = MAX(CASE WHEN t.store = 'Walmart' THEN t.ShippedItems END),
    Walmart_ReturnedItems = MAX(CASE WHEN t.store = 'Walmart' THEN t.ReturnedItems END),
    Lowes_ShippedItems = MAX(CASE WHEN t.store = 'Lowes' THEN t.ShippedItems END),
    Lowes_ReturnedItems = MAX(CASE WHEN t.store = 'Lowes' THEN t.ReturnedItems END),
    HomeDepot_ShippedItems = MAX(CASE WHEN t.store = 'Home Depot' THEN t.ShippedItems END),
    HomeDepot_ReturnedItems = MAX(CASE WHEN t.store = 'Home Depot' THEN t.ReturnedItems END)
FROM
    @t t

HTH, 杰森