teoria de sql y ejercicios
TRANSCRIPT
1. 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 selección 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,NombreCompañía,País 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,NombreCategoría,PrecioUnidad,Suspendido
create view v_productos
as
select NombreProducto,NombreCategoría,PrecioUnidad,Suspendido from Productos p
inner join Categorías c on p.IdCategoría =c.IdCategoría
go
select * from v_productos
order by NombreCategoría,NombreProducto
go
4. Utilizando la vista anterior , crear una vista que muestre el total de productos x categoria
create view total_prodxcateg
as
select NombreCategoría,COUNT(*)as Totalprodxcateg from v_productos
group by NombreCategoría
go
select * from total_prodxcateg
5. Crear una vista que nos devuelva la cantidad de pedidos que tiene cada empleado en los ---años 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 Año_1994,
(select COUNT(*)from v_empleado e where e.Nombre=c.Nombre and YEAR(FechaPedido)=1995)as Año_1995,
(select COUNT(*)from v_empleado e where e.Nombre =c.Nombre and YEAR(FechaPedido)=1996)as Año_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 compañia de envio
create view v_totalpedidos
as
select NombreCompañía,COUNT(*)as Total_Pedidos from v_compañia
group by NombreCompañía
go
select * from v_totalpedidos
Publicado 12th July 2012 por kevin lopez chavez
0
Añadir un comentario
2.
3.
JUL
12
COMBINACION DE TABLAS
Bienvenidos a mi blog !!!!!
Aquí Ud. podrá conocer y aprender un poco mas de SQL SERVER 2008,con ejercicios resueltos y
bien explicados.
Bueno comencemos con lo ejercicios, ya que la teoría ustedes ya saben y si no ??
Me la escriben...
---- Combinación de Tablas -----
1 . Combinación Interna de Tablas
Hay 2 formas de hacerlo: Para este caso lo voy hacer con la tabla Productos y Categorìas
- Primera Forma : (INNER JOIN)
SELECT NOMBRECATEGORÍA,NOMBREPRODUCTO
FROM Productos P INNER JOIN Categorías C
ON P.IdCategoría =C.IdCategoría GO
-Segunda Forma : (WHERE)
SELECT NOMBRECATEGORÍA,NOMBREPRODUCTO
FROM Productos P , Categorías C
WHERE P.IdCategoría =C.IdCategoría
GO
2. Combinación Externa de Tablas
-- IZQUIERDA ---> LISTA TODAS LOS PRODUCTOS QUE NO TIENEN CATEGORÍAS
SELECT NOMBRECATEGORÍA,NOMBREPRODUCTO
FROM Productos P LEFT OUTER JOIN Categorías C
ON P.IdCategoría =C.IdCategoría
GO
---DERECHA ---> LISTA TODAS LA CATEGORÍAS QUE NO TIENES PRODUCTOS
SELECT NOMBRECATEGORÍA,NOMBREPRODUCTO
FROM Productos P RIGHT OUTER JOIN Categorías C
ON P.IdCategoría =C.IdCategoría
GO
---- COMPLETA ----> LISTA TODOS LOS PRODUCTOS CON SUS CATEGORÍAS,
PRODUCTOS QUE NO TIENE CATEGORÍAS
Y LAS CATEGORIAS QUE NO TIENEN PRODUCTOS
SELECT NOMBRECATEGORÍA,NOMBREPRODUCTO
FROM Productos P FULL OUTER JOIN Categorías C
ON P.IdCategoría =C.IdCategoría
GO
Publicado 12th July 2012 por kevin lopez chavez
0
Añadir un comentario
4.
JUL
12
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 código 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
Publicado 12th July 2012 por kevin lopez chavez
0
Añadir un comentario
5.
JUL
12
SUBCONSULTAS
---- SUBCONSULTAS ----
Una subconsulta es una consulta dentro de otra que se puede emplear para obtener totales
y selección de datos de tablas anidadas
EJEMPLOS :
---CONTAR A LOS CLIENTES DE UN DETERMINADO PAÍS---
select distinct País ,(select COUNT(*)
from Clientes c2
where c2.País =c1.País)
as total_clientes
from Clientes c1
order by País
go
---SUMA EL PRECIO DE UNA CATEGORÍA DE PRODUCTOS ---
select Nombrecategoría,(select SUM(PrecioUnidad)from Productos p
where p.IdCategoría = c.IdCategoría )as Suma_PrecioUnidad
from Categorías c
go
---CUENTA LOS PEDIDOS DEL CLIENTE ---
select NombreCompañía ,(select COUNT(*)from Pedidos p where p.IdCliente=c.IdCliente )
as Pedidos_Del_Cliente
from Clientes c
go
---CLIENTES QUE SEAN DE MÉXICO ---
select NombreCompañía as Clientes from Clientes
where IdCliente IN (select IdCliente from Clientes where País='México')
go
---CLIENTES QUE COMPRARON EL PRODUCTO PEZ ESPADA ---
select NombreCompañía 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 AÑO ---
select distinct year(fechaPedido),(select COUNT(*)
from Pedidos d
where year(d.FechaPedido ) = year(p.FechaPedido ))
as Pedidos_X_Año
from Pedidos p
go