----------------------------------- PIVOT
A continuación se presenta una serie de ejemplos para la utilización de PIVOT en SQL Server.
Para ir comprendiendo de manera más fácil, iré realizando ejemplos muy sencillos pero prácticos.
BASE: Se construye una tabla que nos apoyará en el ejemplo
DECLARE @Tabla as table (EnglishDayName varchar (15), Qty smallint)
insert into @Tabla
select 'Saturday' , 54 union all
select 'Wednesday', 15 union all
select 'Monday', 98 union all
select 'Sunday', 45 union all
select 'Friday', 33 union all
select 'Thursday', 1 union all
select 'Tuesday', 450
---------- Listo, ya tenemos nuestra tabla para el ejemplo
select * from @Tabla
Para llamar al operador PIVOT, debe mandar llamar una agregación (SUM, AVG, COUNT etc) necesaria en cualquier valor de columna.
1.- para el siguiente ejemplo se tiene una función de agregación SUM
2.- FOR: Columna que contiene los valores que se convertirán en encabezados de columna
3.- IN [Columna Dinamizada] -- (contenido de la Columna)
4.- Por último deje un nombre de alias al PIVOT
SELECT *
FROM @Tabla
PIVOT
(
SUM(Qty) FOR EnglishDayName IN ( [Sunday],[Monday],[Tuesday],[wednesday], [Thursday],[Friday],[Saturday] )
) AS PV
Resultado:
EJEMPLO 2:
Para el ejemplo dos, voy a agregar otra columna más a la tabla:
Resultado:
ó se puede hacer de la siguiente manera
Resultado:
DECLARE @Tabla as table ([Year] int, EnglishDayName varchar (15), Qty smallint)
insert into @Tabla
select 2015, 'Saturday' , 54 union all
select 2015, 'Wednesday', 15 union all
select 2015, 'Monday', 98 union all
select 2015, 'Sunday', 45 union all
select 2015, 'Friday', 33 union all
select 2015, 'Thursday', 1 union all
select 2015, 'Tuesday', 450 union all
select 2014, 'Saturday' , 9 union all
select 2014, 'Wednesday', 71 union all
select 2014, 'Monday', 98 union all
select 2014, 'Sunday', 88 union all
select 2014, 'Friday', 73 union all
select 2014, 'Thursday', 10 union all
select 2014, 'Tuesday', 45
select * from @Tabla
select *
from @Tabla
PIVOT
(
SUM(Qty) FOR [YEAR] IN ([2015],[2014])
) AS PV
Resultado:
ó se puede hacer de la siguiente manera
select *
from @Tabla
PIVOT
(
SUM(Qty) FOR EnglishDayName IN ( [Sunday],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday] )
) AS PV
EJEMPLO 3
DECLARE @Table as TABLE (Client varchar(20), Product varchar(20), Qty tinyint)
insert into @Table
select 'John' ,'bike' , 1 union all
select 'John' ,'moto' , 3 union all
select 'Karen','moto' , 5 union all
select 'Karen','bike' , 7 union all
select 'John' ,'bike' , 4 union all
select 'Karen','car' , 1 union all
select 'Karen','moto' , 9 union all
select 'Karen','bike' , 3 union all
select 'Karen','moto' , 2 union all
select 'John' ,'moto' , 4
select * from @Table
PIVOT:
Select *
from @Table
PIVOT
(
SUM(Qty) FOR Product IN ( [bike], [moto], [car])
) AS PV
Result:
EXCELENTE APORTE, MUY DETALLADO.
ResponderBorrarGRACIAS.