Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

Trasporre righe in colonne in SQL Server: tre metodi

Ci sono diversi modi per trasformare più righe in colonne. Ecco i tre più comuni.

Usando PIVOT

L'operatore PIVOT di SQL Server trasforma i dati di riga in colonne:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from (
    select value, columnname from yourtable
) d
pivot (
    max(value) for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

Pivot con un numero sconosciuto di colonne

Quando l'insieme di valori columnname non è noto in anticipo, usa SQL dinamico:

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
select @cols = STUFF((
    SELECT ',' + QUOTENAME(ColumnName)
    from yourtable
    group by ColumnName, id
    order by id
    FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

set @query = N'SELECT ' + @cols + N' from (
    select value, ColumnName from yourtable
) x
pivot (
    max(value) for ColumnName in (' + @cols + N')
) p '

exec sp_executesql @query;

Usando una funzione aggregata

Se preferisci evitare PIVOT, puoi combinare un aggregato con un'espressione CASE:

select
    max(case when columnname = 'FirstName'      then value end) Firstname,
    max(case when columnname = 'Amount'         then value end) Amount,
    max(case when columnname = 'PostalCode'     then value end) PostalCode,
    max(case when columnname = 'LastName'       then value end) LastName,
    max(case when columnname = 'AccountNumber'  then value end) AccountNumber
from yourtable

Usando join multipli

Potresti ottenere lo stesso risultato anche con join multipli, anche se avresti bisogno di una colonna per associare ciascuna delle righe. La forma di base sarebbe:

select fn.value as FirstName, a.value as Amount, pc.value as PostalCode,
       ln.value as LastName, an.value as AccountNumber
from yourtable fn
left join yourtable a  on fn.somecol = a.somecol  and a.columnname  = 'Amount'
left join yourtable pc on fn.somecol = pc.somecol and pc.columnname = 'PostalCode'
left join yourtable ln on fn.somecol = ln.somecol and ln.columnname = 'LastName'
left join yourtable an on fn.somecol = an.somecol and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'