Możesz łatwo podzielić YP
ciąg znaków za pomocą LEFT()
, RIGHT()
, SUBSTRING()
, itp. Moja sugestia dotyczyłaby sposobu obsługi UNPIVOT
. Wygląda na to, że masz dużo kolumn do UNPIVOT
więc moja sugestia może polegać na zaimplementowaniu dynamicznego SQL do wykonania tego zapytania. Zrobiłbyś to w ten sposób:
declare @colsUnpivot varchar(max),
@query AS NVARCHAR(MAX),
@cols varchar(max)
select @colsUnpivot = stuff((select ','
+quotename(replace(C.name, 'Qty', ''))
from sys.columns as C
where C.object_id = object_id('yourtable') and
C.name like 'Qty%'
for xml path('')), 1, 1, '')
select @cols = stuff((select ','
+quotename(C.name) + ' as ' + replace(C.name, 'Qty', '')
from sys.columns as C
where C.object_id = object_id('yourtable') and
C.name like 'Qty%'
for xml path('')), 1, 1, '')
set @query
= 'select rowid,
left(YP, 1) YP,
cast(right(YP, len(YP) - 1) as int) period,
Val
from
(
select rowid, ' + @cols + '
from yourtable
) x1
unpivot
(
val for YP IN (' + @colsUnpivot + ')
) u'
exec(@query)