Está en la página 1de 11

VISTAS

----- Vistas ---Una vista es una consulta especial que se emplea para registrar selecciones complejas o que
se usan frecuentemente.
Una vez creada la vista se puede realizar una seleccin de los datos como si fuera esta una
tabla e incluso se puede utilizar para definir procedimientos almacenados.
EJEMPLOS :
1. Crear una vista que liste 3 campos de clientes

create view v_listaclientes


as
select IdCliente,NombreCompaa,Pas from Clientes
go
nota : para ejecutar la vista se hace lo siguiente
select * from v_listaclientes
go

2. Crear una vista que muestre el subtotal de los pedidos


create view v_subtotal
as
select IdPedido,SUM(d.PrecioUnidad * Cantidad * (1-d.Descuento ))as Subtotal
from DetallesDepedidos d
inner join Productos p
on d.IdProducto=p.IdProducto
group by IdPedido
go
select * from v_subtotal
go

3. Crear una vista que


liste NombreProducto,NombreCategora,PrecioUnidad,Suspendido

create view v_productos


as
select NombreProducto,NombreCategora,PrecioUnidad,Suspendido from Productos p
inner join Categoras c on p.IdCategora =c.IdCategora
go

select * from v_productos


order by NombreCategora,NombreProducto
go

4. Utilizando la vista anterior , crear una vista que muestre el total de productos x
categoria
create view total_prodxcateg
as
select NombreCategora,COUNT(*)as Totalprodxcateg from v_productos
group by NombreCategora
go
select * from total_prodxcateg

5. Crear una vista que nos devuelva la cantidad de pedidos que tiene cada empleado en
los
---aos 94,95 y 96

create view v_cant_pedidos


as
select Nombre,(Select COUNT (*)from v_empleado e where e.Nombre=c.Nombre and
YEAR(FechaPedido)=1994) as Ao_1994,
(select COUNT(*)from v_empleado e where e.Nombre=c.Nombre and
YEAR(FechaPedido)=1995)as Ao_1995,
(select COUNT(*)from v_empleado e where e.Nombre =c.Nombre and
YEAR(FechaPedido)=1996)as Ao_1996
from v_empleado c
group by Nombre
select * from v_cant_pedidos

6. Crear una vista que presente el total de pedido que tiene cada compaia de envio

create view v_totalpedidos


as
select NombreCompaa,COUNT(*)as Total_Pedidos from v_compaia
group by NombreCompaa
go
select * from v_totalpedidos

---- Combinacin de Tablas -----

1 . Combinacin Interna de Tablas

Hay 2 formas de hacerlo:


Para este caso lo voy hacer con la tabla Productos y Categoras

- Primera Forma : (INNER JOIN)

SELECT NOMBRECATEGORA,NOMBREPRODUCTO
FROM Productos P INNER JOIN Categoras C
ON P.IdCategora =C.IdCategora
GO

-Segunda Forma : (WHERE)

SELECT NOMBRECATEGORA,NOMBREPRODUCTO
FROM Productos P , Categoras C
WHERE P.IdCategora =C.IdCategora
GO

2. Combinacin Externa de Tablas


-- IZQUIERDA ---> LISTA TODAS LOS PRODUCTOS QUE NO TIENEN CATEGORAS
SELECT NOMBRECATEGORA,NOMBREPRODUCTO
FROM Productos P LEFT OUTER JOIN Categoras C
ON P.IdCategora =C.IdCategora
GO
---DERECHA ---> LISTA TODAS LA CATEGORAS QUE NO TIENES PRODUCTOS
SELECT NOMBRECATEGORA,NOMBREPRODUCTO
FROM Productos P RIGHT OUTER JOIN Categoras C
ON P.IdCategora =C.IdCategora
GO
---- COMPLETA ----> LISTA TODOS LOS PRODUCTOS CON SUS CATEGORAS,
PRODUCTOS QUE NO TIENE CATEGORAS
Y LAS CATEGORIAS QUE NO TIENEN PRODUCTOS

SELECT NOMBRECATEGORA,NOMBREPRODUCTO
FROM Productos P FULL OUTER JOIN Categoras C
ON P.IdCategora =C.IdCategora
GO

CREACION DE BASE DE DATOS

---- CREACION DE BASE DE DATOS ---Creamos la base de datos llamada ventas

create database ventas


go
use ventas
go
Para crear la tabla tienda preguntamos si existe, si existe la borramos y la creamos
para evitar errores al momento de ejecutar varias veces

if exists(select * from sysobjects where type ='u' and name ='Tienda')


drop table Tienda
go
create table Tienda
(
IdTienda int identity(1,1)primary key,
NombreTienda varchar(30) not null,
Estado varchar(10)not null)
go
nota :
- estoy estableciendo que el campo IdTienda es llave primaria
- estoy estableciendo que el campo NombreTienda tiene que ser llenado obligatoriamente al
momento
de ingresar un nuevo registro
Creamos la tabla TiendaProducto

if exists(select * from sysobjects where type='u' and name ='TiendaProducto')


drop table TiendaProducto
go
create table TiendaProducto
(
IdTienda int not null,

IdProducto int not null,


Cantidad int )
go
-estoy asignando dos llaves primarias a la tabla TiendaProducto
alter table TiendaProducto add constraint pk_TiendaProducto primary
key(IdTienda,IdProducto)
-estoy relacionando el campo IdTienda que es llave primaria con el campo IdTienda de
la tabla Tienda
alter table TiendaProducto add constraint fk_TiendaProducto foreign key(IdTienda) references
Tienda(IdTienda)
-estoy relacionando el campo IdProducto que es llave primaria con el
campo IdProducto de la tabla Producto
alter table TiendaProducto add constraint fk_TiendaProduct foreign key(IdProducto) references
Producto(IdProducto)
Creamos la tabla Producto

if exists(select * from sysobjects where type='u' and name ='Producto')


drop table Producto
go
create table Producto
(
IdProducto int identity(1,1)primary key,
NombreProducto char(30) not null,
Precio Money not null)
go
Creamos la tabla Empleado
if exists(select * from sysobjects where type='u' and name ='Empleado')
drop table Empleado
go
create table Empleado
(
IdEmpleado int identity(1,1)primary key,
Nombres char(30) not null,
Apellidos varchar(30)not null,
-relaciono el campo IdTienda de Empleado con IdTienda de Tienda

IdTienda int foreign key references Tienda(IdTienda))


go

Estas lineas de cdigo es para generar el diagrama de tablas relacionadas


exec sp_dbcmptlevel 'ventas','90';
alter authorization on database ::ventas to Sa
exec sp_dbcmptlevel 'ventas','90';
go

SUBCONSULTAS

---- SUBCONSULTAS ---Una subconsulta es una consulta dentro de otra que se puede emplear para obtener totales
y seleccin de datos de tablas anidadas
EJEMPLOS :
---CONTAR A LOS CLIENTES DE UN DETERMINADO PAS--select distinct Pas ,(select COUNT(*)
from Clientes c2
where c2.Pas =c1.Pas)
as total_clientes
from Clientes c1
order by Pas
go
---SUMA EL PRECIO DE UNA CATEGORA DE PRODUCTOS --select Nombrecategora,(select SUM(PrecioUnidad)from Productos p
where p.IdCategora = c.IdCategora )as Suma_PrecioUnidad
from Categoras c
go
---CUENTA LOS PEDIDOS DEL CLIENTE --select NombreCompaa ,(select COUNT(*)from Pedidos p where p.IdCliente=c.IdCliente )
as Pedidos_Del_Cliente
from Clientes c
go
---CLIENTES QUE SEAN DE MXICO --select NombreCompaa as Clientes from Clientes
where IdCliente IN (select IdCliente from Clientes where Pas='Mxico')
go
---CLIENTES QUE COMPRARON EL PRODUCTO PEZ ESPADA --select NombreCompaa as Clientes from Clientes where IdCliente in
(select IdCliente from Pedidos where IdPedido in
(select IdPedido from DetallesDepedidos where IdProducto in
(select IdProducto from Productos where NombreProducto='Pez Espada')))
go

---MUESTRA LA CANTIDAD DE PEDIDOS POR AO --select distinct year(fechaPedido),(select COUNT(*)


from Pedidos d
where year(d.FechaPedido ) = year(p.FechaPedido ))
as Pedidos_X_Ao
from Pedidos p
go

También podría gustarte