Puedes dividir fácilmente el YP
cadena usando LEFT()
, RIGHT()
, SUBSTRING()
, etc. Mi sugerencia sería cómo está manejando su UNPIVOT
. Parece que tienes muchas columnas para UNPIVOT
entonces mi sugerencia podría ser implementar SQL dinámico para realizar esta consulta. Lo harías de esta manera:
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)