Mentre interrogazione di Cletus è corretto, vale la pena sottolineare che è possibile utilizzare la parola chiave UNPIVOT in SQL Server 2005 e versioni successive a fare quasi la stessa cosa:
select
period, nameOfVehicle, value
from T unpivot (
value for nameOfVehicle in ([Car],[Truck],[Boat])
) as U;
La differenza tra la soluzione UNPIVOT e Cletus di è che UNPIVOT non includerà righe per le quali [valore] È NULL. Se avete bisogno di NULL, dovrete essere un po 'subdolo e utilizzare un valore che non può mai verificarsi nella tabella (qui io uso una stringa vuota):
with X(period,Car,Truck,Boat) as (
select period,coalesce(Car,''),coalesce(Truck,''),coalesce(Boat,'')
from T
)
select
period, nameOfVehicle, case when value = '' then null else value end as value
from X unpivot (
value for nameOfVehicle in ([Car],[Truck],[Boat])
) as U;
A seconda delle colonne che terremo dopo unpivoting, questo può essere un'altra opzione (questa soluzione manterrà i valori NULL):
select
period,
nameOfVehicle,
max(case nameOfVehicle
when 'Truck' then Truck
when 'Car' then Car
when 'Boat' then Boat end) as value
from T cross join (
values ('Truck'),('Car'),('Boat')
) as Columns(nameOfVehicle)
group by period, nameOfVehicle;
fonte
2009-08-10 00:45:06
si sta andando ad avere bisogno di essere più preciso circa i dati che avete - come esattamente dovrebbero i contenuti di NameOfVehicle essere determinati, ecc – Amber
I contenuti di NameAndVehicle sono Truck, Car e Boat. – theringostarrs