“Convertir columnas en filas en SQL Server” Código de respuesta

convertir filas en columnas en 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

Convertir columnas en filas en 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

Respuestas similares a “Convertir columnas en filas en SQL Server”

Preguntas similares a “Convertir columnas en filas en SQL Server”

Más respuestas relacionadas con “Convertir columnas en filas en SQL Server” en Sql

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código