/ / pivote en el servidor sql de varias columnas - sql, sql-server, pivot

pivote en el servidor sql de varias columnas - sql, sql-server, pivot

Tengo debajo de la tabla y quiero usar pivote en varias columnas usando suma agregada.

Category        Station1         Station2         Station3
-------------------------------------------------------------
Category1       5.26             6.25             7.28
Category2       4.22             5.00             6.00
Category3       5.00             4.00             8.00
Category1       4.00             7.00             9.00
Category2       2.00             5.00             8.00

Y quiere salida como

My_Station          Category1           Category2             Category3
------------------------------------------------------------------------
Station1            Sum_of_Cat1         Sum_of_Cat2          Sum_of_Cat3
Station2            Sum_of_Cat1         Sum_of_Cat2          Sum_of_Cat3
Station3            Sum_of_Cat1         Sum_of_Cat2          Sum_of_Cat3

Con una sola consulta. No usar ningún bucle

Gracias

Respuestas

0 para la respuesta № 1

Esto no es exactamente un pivote. Podrías quitarte la pata y repivotear. Estoy inclinado a simplemente escribir el SQL para hacerlo:

select station as MyStation,
sum(case when category = "Category1" then value else 0 end) as Category1,
sum(case when category = "Category2" then value else 0 end) as Category2,
sum(case when category = "Category3" then value else 0 end) as Category3
from (select n.station, t.category,
(case when station = "Station1" then Station1
when station = "Station2" then Station2
when station = "Station3" then Station3
end) as value
from t cross join
(select "Station1" as station union all select "Station2" union all select "Station3") n
) t
group by station;

0 para la respuesta № 2

Puedes obtener el resultado quitando las columnas. station1, station2y station3 Primero y luego aplicando la función PIVOT. El proceso Unpivot convierte varias columnas de datos en varias filas.

Hay varios métodos que se pueden utilizar pararetire los datos, incluida la función UNPIVOT, una consulta UNION ALL o el uso de CROSS APPLY. No especificó qué versión de SQL Server está utilizando, pero implementé CROSS APPLY con UNION ALL, por lo que el código es:

select category, my_station, value
from yourtable
cross apply
(
select "station1", station1 union all
select "station2", station2 union all
select "station3", station3
) c (my_station, value);

Ver SQL Fiddle con demostración. Esto da un resultado de:

|  CATEGORY | MY_STATION | VALUE |
| Category1 |   station1 |  5.26 |
| Category1 |   station2 |  6.25 |
| Category1 |   station3 |  7.28 |
| Category2 |   station1 |  4.22 |
| Category2 |   station2 |     5 |

Como puede ver, las columnas de múltiples estaciones ahora están en filas. A continuación, puede aplicar la función PIVOT para convertir el category valores en columnas:

select my_station, category1, category2, category3
from
(
select category, my_station, value
from yourtable
cross apply
(
select "station1", station1 union all
select "station2", station2 union all
select "station3", station3
) c (my_station, value)
) d
pivot
(
sum(value)
for category in (category1, category2, category3)
) piv;

Ver SQL Fiddle con demostración. Esto da un resultado final de:

| MY_STATION | CATEGORY1 | CATEGORY2 | CATEGORY3 |
|   station1 |      9.26 |      6.22 |         5 |
|   station2 |     13.25 |        10 |         4 |
|   station3 |     16.28 |        14 |         8 |