“Konvertieren Sie die Spalten in Zeilen im SQL -Server” Code-Antworten

Umwandeln Sie Zeilen in Spalten auf SQL Server in SQL Server

-- convert rows to columns in sql server (PIVOT)
SELECT Firstname, Amount, PostalCode
FROM (
         SELECT value, columnname
         FROM yourtable
     ) d
PIVOT (
    max(value)
    FOR columnname IN (Firstname, Amount, PostalCode)
) piv;
VasteMonde

Konvertieren Sie die Spalten in Zeilen im SQL -Server

# You can use the UNPIVOT function to convert the columns into rows:

select id, entityId,
  indicatorname,
  indicatorvalue
from yourtable
unpivot
(
  indicatorvalue
  for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;

# Note, the datatypes of the columns you are unpivoting must be the same so you might 
# have to convert the datatypes prior to applying the unpivot.

# You could also use CROSS APPLY with UNION ALL to convert the columns:

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);

# Depending on your version of SQL Server you could even use CROSS APPLY with 
# the VALUES clause:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  values
  ('Indicator1', Indicator1),
  ('Indicator2', Indicator2),
  ('Indicator3', Indicator3),
  ('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);

# Finally, if you have 150 columns to unpivot and 
# you don't want to hard-code the entire query, then you could generate the 
# sql statement using dynamic SQL:

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;
Mappy Show

Ähnliche Antworten wie “Konvertieren Sie die Spalten in Zeilen im SQL -Server”

Fragen ähnlich wie “Konvertieren Sie die Spalten in Zeilen im SQL -Server”

Weitere verwandte Antworten zu “Konvertieren Sie die Spalten in Zeilen im SQL -Server” auf Sql

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen