können Sie verwenden, um die UNPIVOT Funktion, um die Spalten in Zeilen zu konvertieren:
select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;
Hinweis, die Datentypen der Spalten Sie die gleichen sein werden unpivoting müssen, damit Sie die Datentypen umwandeln könnte müssen vor der Anwendung entmutigen.
könnten Sie auch CROSS APPLY
mit UNION verwenden, um alle Spalten zu konvertieren:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
select 'Indicator1', Indicator1 union all
select 'Indicator2', Indicator2 union all
select 'Indicator3', Indicator3 union all
select 'Indicator4', Indicator4
) c (indicatorname, indicatorvalue);
auf Ihrer Version von SQL Server Je könnten Sie sogar CROSS mit der VALUES-Klausel GILT verwenden:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
values
('Indicator1', Indicator1),
('Indicator2', Indicator2),
('Indicator3', Indicator3),
('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);
Schließlich Wenn Sie 150 Spalten zum Entsperren haben und die gesamte Abfrage nicht fest codieren möchten, können Sie die SQL-Anweisung mit dynamischem SQL generieren:
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'yourtable' and
C.column_name like 'Indicator%'
for xml path('')), 1, 1, '')
set @query
= 'select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in ('+ @colsunpivot +')
) u'
exec sp_executesql @query;
Haben Sie sich in [Pivot/Unpivot] (http://msdn.microsoft.com/en-us/library/ms177410 (v = SQL.105) .aspx) noch? –
Am Ende ging es mit der Bluefoot-Lösung. Elegant und funktional. Vielen Dank an alle. – Sergei