SQL查询将下表转换为所需格式

时间:2018-10-11 12:35:18

标签: sql sql-server

在以下问题上需要帮助。请提供一些指示/建议。

将下表转换为如下所示的必需格式:

Transform table 我在下面的链接中创建了表格: https://rextester.com/EEFTL51608

2 个答案:

答案 0 :(得分:2)

请注意,我已将值更改为整数。如果原始表中的数据类型不是数字,那么您将需要执行另一步骤以将其转换为数字,以便能够总结出最终结果

Create table ProdTable
(    
     Product nvarchar(50),
     [2012] int,
     [2013] int ,
     [2014] int ,
     [2015] int ,
)
GO
Insert into ProdTable values ('Cars','100','125','200','175');
Insert into ProdTable values ('shirts','125','75','100','155');
Insert into ProdTable values ('Cars','75','115','100','255');
Insert into ProdTable values ('Pens','140','100','105','185');
Insert into ProdTable values ('Flowers','155','120','145','165');
select * from ProdTable

select *    
from   ProdTable    
       unpivot
       (
           value
           for year in ([2012], [2013], [2014], [2015])
       ) u
       pivot
       (
           sum(value)
           for Product in ([Cars], [shirts], [Pens], [Flowers])
       ) p

答案 1 :(得分:0)

您需要取消枢纽操作,所以我会这样做:

select year, max(case when t.product = 'Cars' then val end) as Cars,
             max(case when t.product = 'shirts' then val end) as shirts,
             max(case when t.product = 'Pens' then val end) as Pens,
             max(case when t.product = 'Flowers' then val end) as Flowers
from table t cross apply
     ( values ('2012', [2012]), ('2013', [2013]), ('2014', [2014]), ('2015', [2015])
     ) tt(year, val)
group by year;