Вы находитесь на странице: 1из 13

BD Aventure Worlds

-------------Ventas mensual en dinero del ao 2007


select mes=MONTH(OrderDate),sum(TotalDue),
datename(MONTH,orderDate)
from Sales.SalesOrderHeader
where year(OrderDate)=2007
group by MONTH(OrderDate), DATENAME(MONTH,OrderDate)
order by MONTH(OrderDate)

-------------mejores 3 meses Ventas mensual en dinero del ao 2007


select top 3 mes=MONTH(OrderDate),sum(TotalDue),
datename(MONTH,orderDate)
from Sales.SalesOrderHeader
where year(OrderDate)=2007
group by MONTH(OrderDate), DATENAME(MONTH,OrderDate)
order by sum(TotalDue) desc

-----------------determinar los 3 mejores territorios de cada ao


select z.*
from(select ROW_NUMBER() over(partition by x.anio order by x.total desc)
as orden, x.*
from
(select anio=YEAR(s.orderdate), t.name, sum(s.TotalDue)
as total
from Sales.SalesOrderHeader s inner join
Sales.SalesTerritory t on
s.TerritoryID=t.TerritoryID
group by t.Name, year(s.OrderDate)) x) z
where z.orden<4
order by z.anio, z.total desc

otra forma
declare @num int; set @num=1
select z.*
from(select ROW_NUMBER() over(partition by x.anio order by x.total desc)
as orden, x.*
from
(select anio=YEAR(s.orderdate), t.name, sum(s.TotalDue)
as total
from Sales.SalesOrderHeader s inner join
Sales.SalesTerritory t on
s.TerritoryID=t.TerritoryID
group by t.Name, year(s.OrderDate)) x) z
where z.orden<=@num
order by z.anio, z.total desc

---------------PRODUCTOS POR DA
select H.OrderDate, D.OrderQty, P.Name
from Sales.SalesOrderHeader H
inner join Sales.SalesOrderDetail D
H.SalesOrderID=D.SalesOrderID

ON

INNER JOIN Production.Product P ON D.ProductID=P.ProductID

----------------UTILIDAD DE VENTA DE PRODUCTOS


select H.OrderDate, D.OrderQty, P.Name,UTIL=D.UnitPrice-P.StandardCost
from Sales.SalesOrderHeader H
inner join Sales.SalesOrderDetail D
H.SalesOrderID=D.SalesOrderID

ON

INNER JOIN Production.Product P ON D.ProductID=P.ProductID

----------------VENTA POR INTERNET Y LOCAL POR AOS


SELECT YEAR(ORDERDATE), [LOCAL]=SUM(CASE WHEN OnlineOrderFlag=0
THEN TotalDue END),
INTERNET=SUM(CASE WHEN OnlineOrderFlag=1 THEN TotalDue
END)
FROM Sales.SalesOrderHeader
GROUP BY YEAR(OrderDate)

------------------------cliente y vendedor -modificar


SELECT
H.SalesOrderID AS 'N Orden',
H.OrderDate AS Fecha,
SUM(D.OrderQty*D.UnitPrice) AS [Importe Vendido],
V.FirstName+' '+V.MiddleName+' '+V.LastName AS Vendedor,
C.FirstName+' '+C.MiddleName+' '+C.LastName AS Cliente
FROM Sales.SalesOrderHeader H

INNER JOIN Sales.SalesOrderDetail D


ON H.SalesOrderID = D.SalesOrderID

INNER JOIN Person.Person V


ON H.SalesPersonID = V.BusinessEntityID

INNER JOIN Person.Person C


ON H.CustomerID = C.BusinessEntityID

GROUP BY H.SalesOrderID, H.OrderDate, V.FirstName+' '+V.MiddleName+'


'+V.LastName, C.FirstName+' '+C.MiddleName+' '+C.LastName
------------------------------------------------------------Mostrar proveedores por ubicacin
En el ejemplo siguiente se enumeran los proveedores y sus direcciones.

SQL
USE AdventureWorks;
GO
SELECT V.VendorID, V.Name AS Vendor, A.AddressLine1, A.AddressLine2,
A.City, SP.Name AS State, CR.Name AS Country
FROM Purchasing.Vendor AS V
JOIN Purchasing.VendorAddress AS VA ON VA.VendorID = V.VendorID
JOIN Person.Address AS A on A.AddressID = VA.AddressID
JOIN Person.StateProvince AS SP on SP.StateProvinceID =
A.StateProvinceID
JOIN Person.CountryRegion AS CR ON CR.CountryRegionCode =
SP.CountryRegionCode
GROUP BY V.VendorID, V.Name, A.AddressLine1, A.AddressLine2, A.City,
SP.Name, CR.Name
ORDER BY V.VendorID;
GO

B. Mostrar productos suministrados por los proveedores


En el ejemplo siguiente se enumeran los productos que los proveedores
suministran a Adventure Works Cycles.
SQL
USE AdventureWorks;
GO
SELECT P.ProductNumber, P.Name AS Product, V.Name AS Vendor,
PV.LastReceiptCost
FROM Production.Product AS P
JOIN Purchasing.ProductVendor AS PV ON P.ProductID = PV.ProductID
JOIN Purchasing.Vendor AS V ON V.VendorID = PV.VendorID
ORDER BY P.Name ;
GO

C. Mostrar contactos de proveedor por proveedor

En el ejemplo siguiente se enumeran los contactos de los proveedores.


Estos contactos son empleados del proveedor con los que los empleados del
departamento de compras de Adventure Works Cycles interaccionan para
solicitar piezas y productos.
SQL
GO
SELECT V.Name as Vendor, C.FirstName, C.LastName, CT.Name AS Title
FROM Person.Contact AS C
JOIN Purchasing.VendorContact VC ON C.ContactID = VC.ContactID
JOIN Person.ContactType CT ON CT.ContactTypeID = VC.ContactTypeID
JOIN Purchasing.Vendor V ON V.VendorID = VC.VendorID
ORDER BY V.Name;
GO

D. Mostrar compras por proveedor


En el ejemplo siguiente se muestran los proveedores y los pedidos de
compra asociados.
SQL
USE AdventureWorks;
GO
SELECT V.Name AS Vendor, SUM(PH.TotalDue)AS [Total Purchase],
AVG(PH.TotalDue)AS [Average Purchase], MIN(PH.TotalDue)
AS [Minimum Purchase], MAX(PH.TotalDue)AS [Maximum Purchase]
FROM Purchasing.Vendor AS V
JOIN Purchasing.PurchaseOrderHeader AS PH ON V.VendorID =
PH.VendorID
GROUP BY V.Name
ORDER BY V.Name;
GO

------------------------------PRODUCTOS
Mostrar productos por categora, subcategora y modelo

En el ejemplo siguiente se enumeran los productos por categora,


subcategora y modelo. Los productos que no estn clasificados no se
incluyen. Para incluir todos los productos, cambie la unin de
ProductCategory por una unin completa.
SQL
USE AdventureWorks;
GO
SELECT PC.Name AS Category, PSC.Name AS Subcategory,
PM.Name AS Model, P.Name AS Product
FROM Production.Product AS P
FULL JOIN Production.ProductModel AS PM ON PM.ProductModelID =
P.ProductModelID
FULL JOIN Production.ProductSubcategory AS PSC ON
PSC.ProductSubcategoryID = P.ProductSubcategoryID
JOIN Production.ProductCategory AS PC ON PC.ProductCategoryID =
PSC.ProductCategoryID
ORDER BY PC.Name, PSC.Name ;
GO

B. Mostrar las descripciones de los productos por modelo de producto


Las descripciones de los productos se crean para cada modelo de producto.
Cada descripcin est disponible en varios idiomas. En el ejemplo siguiente
se muestra cada descripcin de producto en cada uno de los idiomas.
Nota Nota
Es posible que algunos idiomas no se muestren correctamente si no se han
instalado los archivos de soporte de idioma para los idiomas complejos de
scripts e idiomas asiticos. Para instalar estos archivos, vea la
documentacin de Windows en Opciones regionales y de idioma.
SQL
USE AdventureWorks;
GO
SELECT PM.ProductModelID, PM.Name AS [Product Model], Description,
PL.CultureID, CL.Name AS Language
FROM Production.ProductModel AS PM
JOIN Production.ProductModelProductDescriptionCulture AS PL
ON PM.ProductModelID = PL.ProductModelID

JOIN Production.Culture AS CL ON CL.CultureID = PL.CultureID


JOIN Production.ProductDescription AS PD
ON PD.ProductDescriptionID = PL.ProductDescriptionID
ORDER BY PM.ProductModelID ;
GO

A. Mostrar una lista de materiales de un solo nivel para un producto padre


En el ejemplo siguiente se muestran todos los componentes que se utilizan
para crear un producto padre especfico: ProductAssemblyID.
SQL
USE AdventureWorks;
GO
WITH Parts(AssemblyID, ComponentID, PerAssemblyQty, EndDate,
ComponentLevel) AS
(
SELECT b.ProductAssemblyID, b.ComponentID, b.PerAssemblyQty,
b.EndDate, 0 AS ComponentLevel
FROM Production.BillOfMaterials AS b
WHERE b.ProductAssemblyID = 800
AND b.EndDate IS NULL
UNION ALL
SELECT bom.ProductAssemblyID, bom.ComponentID, p.PerAssemblyQty,
bom.EndDate, ComponentLevel + 1
FROM Production.BillOfMaterials AS bom
INNER JOIN Parts AS p
ON bom.ProductAssemblyID = p.ComponentID
AND bom.EndDate IS NULL
)
SELECT AssemblyID, ComponentID, Name, PerAssemblyQty, EndDate,
ComponentLevel
FROM Parts AS p
INNER JOIN Production.Product AS pr

ON p.ComponentID = pr.ProductID
ORDER BY ComponentLevel, AssemblyID, ComponentID;
GO
----------------------------------------------------------------------- Ventas y marketing
Mostrar clientes individuales (consumidores)
En el ejemplo siguiente se devuelven el nombre y los apellidos de todos los
clientes clasificados como clientes individuales (CustomerType = 'I').
SQL
USE AdventureWorks;
GO
SELECT FirstName, LastName
FROM Person.Contact AS C
JOIN Sales.Individual AS I
ON C.ContactID = I.ContactID
JOIN Sales.Customer AS Cu
ON I.CustomerID = Cu.CustomerID
WHERE Cu.CustomerType = 'I'
ORDER BY LastName, FirstName ;
GO

B. Mostrar datos de direccin de clientes individuales


En el ejemplo siguiente se enumeran los nombres y las direcciones de todos
los clientes individuales.
SQL
USE AdventureWorks;
GO
SELECT I.CustomerID, C.FirstName, C.LastName, A.AddressLine1, A.City,
SP.Name AS State, CR.Name AS CountryRegion
FROM Person.Contact AS C
JOIN Sales.Individual AS I ON C.ContactID = I.ContactID
JOIN Sales.CustomerAddress AS CA ON CA.CustomerID = I.CustomerID
JOIN Person.Address AS A ON A.AddressID = CA.AddressID

JOIN Person.StateProvince SP ON
SP.StateProvinceID = A.StateProvinceID
JOIN Person.CountryRegion CR ON
CR.CountryRegionCode = SP.CountryRegionCode
ORDER BY I.CustomerID ;
GO

C. Mostrar clientes de tipo tienda de venta al por menor y venta al por


mayor
En el ejemplo siguiente se devuelve el nombre todos los clientes clasificados
como tienda (CustomerType = 'S').
SQL
USE AdventureWorks;
GO
SELECT Name
FROM Sales.Store AS S
JOIN Sales.Customer AS C
ON S.CustomerID = C.CustomerID
WHERE C.CustomerType = N'S'
ORDER BY Name ;
GO
GO

D. Mostrar contactos de tienda por tienda


En el ejemplo siguiente se devuelve el nombre de todos los clientes tipo
tienda y los nombres y cargos de los empleados de las tiendas autorizados
para comprar productos de Adventure Works Cycles en nombre de su
empresa.
SQL
USE AdventureWorks;
GO
SELECT S.Name AS Store, C.FirstName, C.LastName, CT.Name AS Title

FROM Person.Contact AS C
JOIN Sales.StoreContact AS SC ON C.ContactID = SC.ContactID
JOIN Person.ContactType AS CT ON
CT.ContactTypeID = SC.ContactTypeID
JOIN Sales.Store AS S ON S.CustomerID = SC.CustomerID
ORDER BY S.Name ;
GO

E. Mostrar las ventas por tienda


En el ejemplo siguiente se enumeran los clientes tipo tienda y los pedidos
de venta asociados.
SQL
USE AdventureWorks;
GO
SELECT Name, SalesOrderNumber, OrderDate, TotalDue
FROM Sales.Store AS S
JOIN Sales.SalesOrderHeader AS SO ON S.CustomerID = SO.CustomerID
ORDER BY Name, OrderDate ;
GO

---------------------------------fabricacin
Mostrar una lista de materiales de varios niveles para un producto padre
En el ejemplo siguiente se muestran todos los componentes que se utilizan
para crear un producto padre especfico: ProductAssemblyID.
SQL
USE AdventureWorks;
GO
WITH Parts(AssemblyID, ComponentID, PerAssemblyQty, EndDate,
ComponentLevel) AS
(
SELECT b.ProductAssemblyID, b.ComponentID, b.PerAssemblyQty,
b.EndDate, 0 AS ComponentLevel

FROM Production.BillOfMaterials AS b
WHERE b.ProductAssemblyID = 800
AND b.EndDate IS NULL
UNION ALL
SELECT bom.ProductAssemblyID, bom.ComponentID, p.PerAssemblyQty,
bom.EndDate, ComponentLevel + 1
FROM Production.BillOfMaterials AS bom
INNER JOIN Parts AS p
ON bom.ProductAssemblyID = p.ComponentID
AND bom.EndDate IS NULL
)
SELECT AssemblyID, ComponentID, Name, PerAssemblyQty, EndDate,
ComponentLevel
FROM Parts AS p
INNER JOIN Production.Product AS pr
ON p.ComponentID = pr.ProductID
ORDER BY ComponentLevel, AssemblyID, ComponentID;
GO

B. Mostrar el inventario de productos


En el ejemplo siguiente se indica la cantidad que hay disponible para cada
producto por ubicacin en el inventario. Los productos pueden hallarse en
varias ubicaciones.
SQL
USE AdventureWorks;
GO
SELECT P.Name AS Product, L.Name AS [Inventory Location],
SUM(PI.Quantity)AS [Qty Available]
FROM Production.Product AS P
JOIN Production.ProductInventory AS PI ON P.ProductID = PI.ProductID
JOIN Production.Location AS L ON PI.LocationID = L.LocationID
GROUP BY P.Name, L.Name

ORDER BY P.Name ;
GO

C. Mostrar los pedidos de trabajo por producto


En el ejemplo siguiente se enumeran todos los pedidos de trabajo para los
productos de las subcategoras Mountain Bike (1), Road Bike (2) y Touring
Bike (3).
SQL
USE AdventureWorks;
GO
SELECT WorkOrderID, P.Name AS Product, OrderQty, DueDate
FROM Production.WorkOrder W
JOIN Production.Product P ON W.ProductID = P.ProductID
WHERE P.ProductSubcategoryID IN (1, 2, 3)
ORDER BY P.Name, DueDate ;
GO

F. Mostrar tiendas por ubicacin


En el ejemplo siguiente se indica el nombre del cliente tipo tienda, la ciudad,
el estado y el pas o regin.
SQL
USE AdventureWorks;
GO
SELECT S.CustomerID, S.Name AS Store, A.City, SP.Name AS State, CR.Name
AS CountryRegion
FROM Sales.Store AS S
JOIN Sales.CustomerAddress AS CA ON CA.CustomerID = S.CustomerID
JOIN Person.Address AS A ON A.AddressID = CA.AddressID
JOIN Person.StateProvince SP ON
SP.StateProvinceID = A.StateProvinceID
JOIN Person.CountryRegion CR ON
CR.CountryRegionCode = SP.CountryRegionCode

ORDER BY S.CustomerID ;
GO
GO
---------------------------------------------------------------

Вам также может понравиться