无法在SQL中进行透视

时间:2018-04-04 07:21:58

标签: sql sql-server tsql pivot unpivot

以下是我的表格品牌年度

 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

2 个答案:

答案 0 :(得分:1)

如果您正在使用SQL Server,则可以使用 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 (即{{1与

答案 1 :(得分:0)

从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

Saravanan