Sie sind auf Seite 1von 4

-- Gestion II - 21/05/2015

-- consultas usando varias tablas.


-- estructura del proyecto
use Northwind
go
-- Consultas varias tablas
select * from Products /*NO UTILIZAR PARA MOSTRAR TODOS LOS CAMPOS*/
go
SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice,
UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued FROM Products
GO /*SE DEBE UTILIZAR TODOS LOS ATRIBUTOS*/
-- ALGUNOS CAMPOS
SELECT [ProductID],[ProductName],[UnitPrice] FROM Products
ORDER BY [ProductName]
GO
SELECT [ProductID] AS 'CODIGO' , [ProductName] 'DESCRIPCION',
[UnitsInStock] STOCK, [UnitPrice] AS 'PRECIO UNITARIO' FROM Products
GO
--FILTROS: WHERE CONDICION
-- CONDICION , COMPRAR EL CAMPO CON UN DATO DEL MISMO TIPO
-- OPERADORES: =,>,<,>=,<=,<>, LIKE, IN, BETWEEN(ENTRE UN RANGO DE VALORES)
-- AND, OR
-- LISTAR LOS PRODUCTOS DESCONTINUADOS DE LAS CATEGORIAS 1,6,7
SELECT * FROM Products where Discontinued=1 and (CategoryID=1 or CategoryID=6 or
CategoryID=7)
SELECT * FROM Products where Discontinued=1 and CategoryID in (1,6,7)
-- listar los productos con precios entre 10 y 50 incluyendo el nombre de la categoria
select ProductID,ProductName,UnitPrice,UnitPrice, c.CategoryName ,s.CompanyName
from Products P
inner join Categories C on p.CategoryID =c.CategoryID
inner join Suppliers S on S.SupplierID = P.SupplierID
-- funciones de agregado: Sum, Avd, Max, Min, Count
-- cuantos productos hay registrados
select count(*) from Products
go
-- cuantos empleados hay registrados
select count(*) from Employees
go
-- cuantos productos hay de cada categoria
select c.categoryID, c.CategoryName, count(P.CategoryID) as 'Cantidad'
from Categories as C join Products as P
on C.CategoryID=P.CategoryID
group by C.CategoryID, C.CategoryName
order by 'Cantidad' desc
go
-- campos calculados
-- listar los empleados (combre completo) y la cantidad de ordenes generadas
select * from Employees
select E.EmployeeID as 'Codigo de empleado', E.LastName+space(1)+FirstName as
'Empleado' , E.Address as 'Direccion', count(O.EmployeeID) as 'Cantidad', sum(O.Freight) as
'Monto Total'
from Employees as E join Orders as O
on E.EmployeeID = O.EmployeeID
group by O.EmployeeID,E.LastName+space(1)+FirstName,E.Address,E.EmployeeID
having count(O.EmployeeID)>100
order by count(O.EmployeeID) desc

go
-- listar los clinetes (customers) y el toptal de compras por ao
-- por cada ao mostrar el subtotal , al final el total general
select c.CustomerID,C.CompanyName, sum(O.Freight) as 'Total',
year(O.OrderDate)as 'Ao'
from Customers as C join Orders as O on C.CustomerID = O.CustomerID
group by C.CustomerID, C. CompanyName,year(O.OrderDate)
order by year(O.OrderDate),Total desc
GO
-- LISTAR
select c.CustomerID,C.CompanyName, sum(O.Freight) as 'Total',
year(O.OrderDate)as 'Ao'
from Customers as C join Orders as O on C.CustomerID = O.CustomerID
group by C.CustomerID, C. CompanyName,year(O.OrderDate)
order by year(O.OrderDate),Total desc
GO
-- Gestion 2 - 28/05/2015
-- CONSULTAS USANDO JOIN
-- SUBCONSULTAS
-- FUNCIONES DEFINIDAS POR EL USUARIO
-- TABLAS TEMPORALES
-- USO DE SP EN VISUAL STUDIOR
USE Northwind
GO
-- LISTAR LAS ORDENES DE AGOSTO 1997
-- INCLUYENDO EL CLIENTE Y EL EMPLEADO
SELECT O.OrderID AS 'N DE ORDEN',
O.OrderDate AS 'FECHA',
O.Freight AS 'MONTO',
e.LastName +SPACE(1)+ E.FirstName AS 'NOMBRE EMPLEADO',
-- EMPLEADO = e.LastName +SPACE(1)+ E.FirstName
C.ContactName AS 'NOMBRE USUARIO'
FROM Orders AS O
JOIN Employees AS E ON O.EmployeeID = e.EmployeeID
JOIN Customers AS C ON O.CustomerID=c.CustomerID
WHERE YEAR(O.OrderDate)=1997 AND MONTH(O.OrderDate)=8
GO
-- SUBCONSULTAS
/* -- DOSTIPOS
1. IN LINE, INCLUIDA EN LA LISTA DE CAMPOS
DE UN SELECT
SELECT CAMPO1,(SELECT...), CAMPO4 FROM TABLA
2. EN LA CLAUSULA WHERE
SELECT CAMPO1,... CAMPO4 FROM TABLA WHERE
CAMPOfILTRO OPERADOR(SELECT ...)
*/
-- LISTADO DE LOS CLIENTES DE BRAZIL QUE COMPRARON EN 1998
-- primero: cuales son los codigos de los clientes de brazil
select C.CustomerID from Customers as C where country='Brazil'
go
-- listado de las ordenes de 1998 de los clientes de blazil
select c.CustomerID as 'Codigo',

c.CompanyName as 'Cliente',
count(o.OrderID ) as 'Cantidad de Orden',
sum(o.Freight) as 'Monto total',
YEAR (o.OrderDate) as 'Ao',
c.Country as 'Pais'
from Orders as o join Customers as C on O.CustomerID=C.CustomerID
where year(o.OrderDate) = 1998
and
o.CustomerID in (select C.CustomerID from Customers as C where country='Brazil')
group by C.CustomerID,c.CompanyName, year(o.OrderDate), C.Country
order by c.CompanyName
go

-- Estructura de la base de datos


sp_helpdb Colegio
go
-- Agregar 02 archivos grupo SOPORTE en D:\Redes
xp_create_subdir 'D:\Redes'
go
alter database Colegio add file
(Name='Colegio15', Filename='D:\Redes\Colegio15.ndf'),
(Name='Colegio20', Filename='D:\Redes\Colegio20.ndf')
to filegroup SOPORTE
go
-- Indices por varios campos
create index EmpleadosNombreCompletoIDXa
on Empleados (EmpleadosPaterno,EmpleadosMaterno,EmpleadosNombres)
go
-- Crear tabla Sucursales en el esquema Ventas, grupo CONTABLE
Create table Ventas.Sucursales
(
SucursalesCodigo nchar(3) not null,
SucursalesDescripcion nvarchar(50)
constraint SucursalesPK Primary key (SucursalesCodigo)
) on CONTABLE
go
-- Listar los registros de Sucursales
select * from Ventas.Sucursales
go
-- Crear esquema Configuracion y pasar la tabla Suscursales
-- al esquema creado
Create schema Configuracion
go
Alter schema Configuracion transfer Ventas.Sucursales
go
-- Visualizar los datos XML
SELECT * FROM Empleados FOR XML AUTO

go
-- Insertar varios
insert into Aulas (AulasDescripcion)
Values ('Segundo grado'),('Tercer grado'),('Cuarto grado'),
('Quinto grado'),('Sexto grado')
go