【SQL SERVER】行列转换

1.行转列PIVOT

select id,[2018-01-01],[2018-01-02],[2018-01-03]
into #tbl
from (
	--源数据表
	select id,charge,date from #c where date between '2018-01-01' and '2018-01-04'
	) t
pivot
(
	--转后的值或待转的值 for(转置后列名所在的列) in (转置后的列名)
	sum(charge) for [date] in([2018-01-01],[2018-01-02],[2018-01-03]) 
)tbl

2.列转行UNPIVOT

select date,charge,id
from #tbl --源数据表
UNPIVOT
(	--[转前列的值在转后放置的列名] for [转前列名在转后放置的列名] in([转前列名列表],[]...)
	--值 的 列 in(哪些列)
	charge for date in([2018-01-01],[2018-01-02],[2018-01-03]) 
) t

 

你可能感兴趣的:(sql)