SQL PIVOT 行转列的应用

行转列方法:

1、case when 这个很容易理解,这里不做过多介绍;

2、PIVOT 结果不需要像case when 一样求和

直接上代码

select 
UPC
,ItemNbr
,StoreNbr
,[year]
,[month] 
,isnull([1],0) d01
,isnull([2]-[1],0) d02
,isnull([3]-[2],0) d03
,isnull([4]-[3],0) d04
,isnull([5]-[4],0) d05
,isnull([6]-[5],0) d06
,isnull([7]-[6],0) d07
,isnull([8]-[7],0) d08
,isnull([9]-[8],0) d09
,isnull([10]-[9],0) d10
,isnull([11]-[10],0) d11
,isnull([12]-[11],0) d12
,isnull([13]-[12],0) d13
,isnull([14]-[13],0) d14
,isnull([15]-[14],0) d15
,isnull([16]-[15],0) d16
,isnull([17]-[16],0) d17
,isnull([18]-[17],0) d18
,isnull([19]-[18],0) d19
,isnull([20]-[19],0) d20
,isnull([21]-[20],0) d21
,isnull([22]-[21],0) d22
,isnull([23]-[22],0) d23
,isnull([24]-[23],0) d24
,isnull([25]-[24],0) d25
,isnull([26]-[25],0) d26
,isnull([27]-[26],0) d27
,isnull([28]-[27],0) d28
,isnull([29]-[28],0) d29
,isnull([30]-[29],0) d30
,isnull([31]-[30],0) d31
-- ,[1],[2],[3],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31]
from(
	select 
	t.UPC
	,t.ItemNbr
	,t.StoreNbr
	,t.[year]
	,t.[month] 
	,t.[day]
	,POSSales
	from jxl_posWMTNew t
	where year = 2022 and month = 3
-- 	and UPC = '0040020428840'
	and StoreNbr = 2068
)a
PIVOT(
	SUM(POSSales)
  FOR day IN
	([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS b

结果

猜你喜欢

转载自blog.csdn.net/qq_41674785/article/details/123521033