无法在 SQL 中旋转

Not able to Pivot in SQL

下面是我的table品牌年份

 Brand   year   Tag        Jan   Feb  
------------------------------------- 
 Brand1  2017   Secondary  4     9     
 Brand1  2017   Primary    11    56     
 Brand1  2016   Secondary  0     2     

我的输出应该如下所示:

 Brand   year   Month   Secondary   Primary
--------------------------------------------
 Brand1  2017   Jan     4           11
 Brand1  2017   Feb     9           56
 Brand1  2016   Jan     0           NULL
 Brand1  2016   Feb     2           NULL

我想通过 SQL

如果您正在使用 SQL 服务器,您可以使用 apply 运算符

select t.Brand, t.year, a.Months,
       max(case when t.tag = 'Secondary' then a.Value end)  Secondary,
       max(case when t.tag = 'Primary  ' then a.Value end)  [Primary]
from table t
cross apply (values (Jan, 'Jan'), (Feb, 'Feb'))a(Value, Months)
group by t.Brand, t.year, a.Months
order by 2 desc, 4 asc

但是,上面的操作同时进行了 pivoting(即您可以看到带有 max() 函数的条件聚合)以及 unpivoting(即 cross apply)和

从 Yogesh Sharma 稍作修改:

select brand,year,month,
max(case when a.tag='secondary' then [primary]  end) as secondary,
max(case when a.tag='primary' then [primary]  end) as [primary]

from
(select brand,
year,
tag,
'jan' as month,
 jan as [primary]
from pivot_int
union
select brand,
year,
tag,
'feb' as month,
 feb as secondary
 from pivot_int
 )a
 group by brand,year,month
 order by 2 desc,4 asc

http://sqlfiddle.com/#!18/57427/32

萨拉瓦南