を「年#」が、顧客のライフタイム値または相対に基づく場合顧客の経験がない場合だけを削除するPartition By Customer
簡単に列数を増やしたり、動的にすることもできます。
あなたは2017年に新規顧客を気づくでしょうし、彼のYEAR1は2017
Declare @YourTable table (customer varchar(25),[0] int,[1] money,[2] money,[3] money,[4] money,[5] money,[6] money,[7] money,[8] money,[9] money,[10] money,[11] money,[12] money)
Insert Into @YourTable values
('VALLERO' ,2014 ,634.150000 ,560.740000 ,254.670000 ,370.292500 ,99.225000 ,157.426666 ,358.650000 ,190.925000 ,767.515000 ,71.665000 ,587.305000 ,615.525000),
('VALLERO' ,2015 ,634.150000 ,560.740000 ,254.670000 ,370.292500 ,99.225000 ,157.426666 ,358.650000 ,190.925000 ,767.515000 ,71.665000 ,587.305000 ,615.525000),
('NewCust' ,2017 ,500.000000 ,650.000000 ,null ,null ,null ,null ,null ,null ,null ,null ,null ,null )
Select Customer
,Year1 = max(case when YearNr= 1 then [0] end)
,Total1 = sum(case when YearNr= 1 then Value end)
,Year2 = max(case when YearNr= 2 then [0] end)
,Total2 = sum(case when YearNr= 2 then Value end)
From (
Select Customer
,YearNr=Dense_Rank() over (Partition By Customer Order by [0])
,[0]
,Value
From @YourTable A
UnPivot (Value for Item in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) u
) A
Group By Customer
戻り
感謝です!これは私が本当に私が表示する必要があるものに近いです。私はそれを設定しようとしていましたが、 "year1"のような列には1年しか入ることができないように設定しましたが、 "2014"と "year2"は2015を保持します。その年の彼らは "null"を持っていました。 – mfoehrer