miércoles, 31 de octubre de 2007

Pivot en SQL 2005

Aca un ejemplo de la sentencia PIVOT.


CREATE TABLE [dbo].[Productos](
[IdProducto] [int] NULL,
[Descripcion] [nvarchar](255) NULL,
[IdRubro] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Rubros](
[idRubro] [int] NULL,
[Descripcion] [nvarchar](255) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Vendedores](
[IDVendedor] [int] NULL,
[Descripcion] [nvarchar](255) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Ventas](
[IdVendedor] [int] NULL,
[IdProducto] [int] NULL,
[Cantidad] [int] NULL,
[Fecha] [datetime] NULL
) ON [PRIMARY]


Insert into Rubros (idRubro,Descripcion) values (1 ,'Perfumes')
Insert into Rubros (idRubro,Descripcion) values (2 ,'Desodorantes')
Insert into Rubros (idRubro,Descripcion) values (3 ,'Cremas')

Insert into Vendedores (idVendedor,Descripcion) values (1 ,'Juan Perez')
Insert into Vendedores (idVendedor,Descripcion) values (2 ,'Maria Vazquez')
Insert into Vendedores (idVendedor,Descripcion) values (3 ,'Rocio Marquez')

Insert into Productos (idProducto,Descripcion,IdRubro) values (1 ,'Perfume Hombre',1 )
Insert into Productos (idProducto,Descripcion,IdRubro) values (2 ,'Perfume Mujer',1 )
Insert into Productos (idProducto,Descripcion,IdRubro) values (3 ,'Desodorante Hombre',2 )
Insert into Productos (idProducto,Descripcion,IdRubro) values (4 ,'Desodorante Mujer',2 )
Insert into Productos (idProducto,Descripcion,IdRubro) values (5 ,'Crema manos',3 )
Insert into Productos (idProducto,Descripcion,IdRubro) values (6 ,'Crema Cuerpo',3 )

Insert into Ventas (idVendedor,IdProducto,Cantidad,Fecha) values (1 ,1 ,10 ,'01/10/2005')
Insert into Ventas (idVendedor,IdProducto,Cantidad,Fecha) values (2 ,2 ,5 ,'01/10/2005')
Insert into Ventas (idVendedor,IdProducto,Cantidad,Fecha) values (1 ,4 ,20 ,'01/10/2005')
Insert into Ventas (idVendedor,IdProducto,Cantidad,Fecha) values (2 ,5 ,30 ,'01/10/2005')
Insert into Ventas (idVendedor,IdProducto,Cantidad,Fecha) values (3 ,6 ,50 ,'01/10/2005')
Insert into Ventas (idVendedor,IdProducto,Cantidad,Fecha) values (3 ,4 ,100,'01/10/2005')



SELECT Vendedor,isnull([Perfumes],0) as Cremas ,isnull([Desodorantes],0) as Desodorantes,
isnull([Cremas],0) as Perfumes
/*Select que define como se mostraran los tados y por que columna se agrupara (Vendedor)*/

FROM
(
Select
cast(vnd.descripcion as char(20)) Vendedor, Cantidad , cast(rbr.descripcion as char(20))Rubro
From
ventas vts inner join vendedores vnd
on vts.idvendedor=vnd.idvendedor
inner join Productos Prd
on Prd.idproducto=vts.idProducto
Inner join Rubros Rbr on Rbr.idRubro=Prd.idRubro

) po

/*Origen de los Datos*/


PIVOT
(
SUM(cantidad)
FOR Rubro IN
([Cremas] , [Perfumes] , [DEsodorantes])
) AS PVT

2 comentarios:

Omar Diaz Esquivel dijo...

Buena tio.

Gracias por tomarte el tiempo de publicarlo con todas las tablas, se agradece mucho.

Espero sigas implementando el blog.

Unknown dijo...

Grande amigo por publicar este tipo de informacion.