viernes, 22 de marzo de 2013

Consultas SQL con dos tablas


/*==============================================================*/
/* BORRADO DE TABLAS */
/*==============================================================*/

drop table TotPropEmpleado cascade constraints;

drop table ARRIENDO cascade constraints;

drop table CLIENTE cascade constraints;

drop table EMPLEADO cascade constraints;

drop table OFICINA cascade constraints;

drop table PROPIEDAD cascade constraints;

drop table PROPIETARIO cascade constraints;

drop table VISITA cascade constraints;
/*==============================================================*/
/* Tabla: ARRIENDO */
/*==============================================================*/

create table ARRIENDO (
NUMARRIENDO INTEGER not null,
NUMPROPIEDAD CHAR(4),
NUMCLIENTE CHAR(4),
RENTA FLOAT,
FORMAPAGO CHAR(10),
DEPOSITO FLOAT,
PAGADO CHAR(1),
INICIORENTA DATE,
FINRENTA DATE,
constraint PK_ARRIENDO primary key (NUMARRIENDO)
);

/*==============================================================*/
/* Tabla: CLIENTE */
/*==============================================================*/
create table CLIENTE (
NUMCLIENTE CHAR(4) not null,
NOMBRE CHAR(30),
APELLIDO CHAR(30),
DIRECCION CHAR(35),
TELEFONO CHAR(10),
TIPOPREF CHAR(25),
MAXRENT FLOAT,
constraint PK_CLIENTE primary key (NUMCLIENTE)
);

/*==============================================================*/
/* Tabla: EMPLEADO */
/*==============================================================*/
create table EMPLEADO (
NUMEMPLEADO CHAR(4) not null,
NOMBRE CHAR(30),
APELLIDO CHAR(30),
CARGO CHAR(35),
SEXO CHAR(1),
FECHNAC DATE,
SALARIO FLOAT,
NUMOFICINA CHAR(4),
constraint PK_EMPLEADO primary key (NUMEMPLEADO)
);

/*==============================================================*/
/* Tabla: OFICINA */
/*==============================================================*/
create table OFICINA (
NUMOFICINA CHAR(4) not null,
CALLE CHAR(30),
CIUDAD CHAR(25),
CODIGOPOSTAL CHAR(10),
constraint PK_OFICINA primary key (NUMOFICINA)
);

/*==============================================================*/
/* Tabla: PROPIEDAD */
/*==============================================================*/
create table PROPIEDAD (
NUMPROPIEDAD CHAR(4) not null,
CALLE CHAR(30),
CIUDAD CHAR(25),
CODIGOPOSTAL CHAR(10),
TIPO CHAR(25),
HAB INTEGER,
RENTA FLOAT,
NUMPROPIETARIO CHAR(4),
NUMEMPLEADO CHAR(4),
constraint PK_PROPIEDAD primary key (NUMPROPIEDAD)
);

/*==============================================================*/
/* Tabla: PROPIETARIO */
/*==============================================================*/

create table PROPIETARIO (
NUMPROPIETARIO CHAR(4) not null,
NOMBRE CHAR(30),
APELLIDO char(30),
DIRECCION CHAR(30),
TELEFONO CHAR(10),
constraint PK_PROPIETARIO primary key (NUMPROPIETARIO)
);

/*==============================================================*/
/* Tabla: VISITA */
/*==============================================================*/
create table VISITA (
NUMCLIENTE CHAR(4) not null,
NUMPROPIEDAD CHAR(4) not null,
FECHA DATE not null,
COMENTARIO VARCHAR2(30),
constraint PK_VISITA primary key (NUMCLIENTE, NUMPROPIEDAD, FECHA)
);

/*==============================================================*/
/* Tabla TotPropEmpleado */
/* Se utiliza para insertar desde otra tabla
/*==============================================================*/

create table TotPropEmpleado (
NUMEMPLEADO CHAR(4) not null,
totProp INTEGER,
constraint PK_TotPropEmpleado primary key (NUMEMPLEADO)
);

alter table TotPropEmpleado
add constraint FK_TotProp_REFERENCE_EMPLEADO foreign key (NUMEMPLEADO)
references EMPLEADO (NUMEMPLEADO);

alter table EMPLEADO
add constraint FK_EMPLEADO_REFERENCE_OFICINA foreign key (NUMOFICINA)
references OFICINA (NUMOFICINA);

alter table PROPIEDAD
add constraint FK_PROPIEDA_REFERENCE_EMPLEADO foreign key (NUMEMPLEADO)
references EMPLEADO (NUMEMPLEADO);

alter table VISITA
add constraint FK_VISITA_REFERENCE_CLIENTE foreign key (NUMCLIENTE)
references CLIENTE (NUMCLIENTE);

alter table VISITA
add constraint FK_VISITA_REFERENCE_PROPIEDA foreign key (NUMPROPIEDAD)
references PROPIEDAD (NUMPROPIEDAD);


/*==============================================================*/
/*= P o b l a m i e n t o d e t a b l a s =*/
/*==============================================================*/

/*==============================================================*/
/* datos: oficina */
/*==============================================================*/
insert into oficina values('B005','16 Holhead','Aberdeem','AB7 5SU');
insert into oficina values('B007','6 Argvill St.','London','NW2');
insert into oficina values('B003','164 Main street','Glasgow','G119Qx');
insert into oficina values('B004','2 Manor Rd','Glasgow','G114Qx');
insert into oficina values('B001','10 Dale Rd','bristol','G12');
insert into oficina values('B002','17 Holhead','Aberdeem','AB7 5SU');
insert into oficina values('B008','7 Argvill St.','London','NW21');
insert into oficina values('B006','163 Main street','Glasgow','G11');
insert into oficina values('B010','2 Manor Rd','Glasgow','G114x');
insert into oficina values('B011','14 Dale Rd','bristol','G2');
insert into oficina values('B017','6 Argvill St.','London','W2');
insert into oficina values('B013','166 Main street','Glasgow','9Qx');
insert into oficina values('B014','3 Manor Rd','Glasgow','Qx');
insert into oficina values('B012','11 Dale Rd','bristol','GH2');
insert into oficina values('B015','Costanera 25','Valdivia','0324');
insert into oficina values('B115','Picarte 124','Valdivia','0324');
insert into oficina values('B215','El Morro 110','Arica','10300');
insert into oficina values('B315','El Vergel 1500','Arica','123123');
insert into oficina values('B415','Av. Walker Martinez 1360','Santiago','W101');
insert into oficina values('B515','Av. Antonio Varas 929','Santiago','W101');

/*==============================================================*/
/* datos: cliente */
/*==============================================================*/
insert into cliente values('CR76','Jhon','Kay','56 High ST,Londonn,SW14EH','0207774563','Departamento',450);
insert into cliente values('CR56','Aline','Stewart','64 Fern Dr, Glasgow G42 OBL','0141324182','Departamento',350);
insert into cliente values('CR74','Mike','Ritchie','63 Well St, Glasgow,G42','0141943742','Casa',750);
insert into cliente values('CR62','Mary','Tregear','12 Park PI, Glasgow, G40QR','0141225742','Departamento',600);
insert into cliente values('CR78','Juan','Kayser','55 High ST,Londonn,SW14EH','0207774564','Departamento',450);
insert into cliente values('CR57','Alicia','Soto','63 Fern Dr,. GlasgowG42 OBL','0141324183','Departamento',350);
insert into cliente values('CR72','Miguel','Torres','62 Well St, Glasgow,G42','0141943740','Casa',750);
insert into cliente values('CR63','Maria','Perez','13 Park PI, Glasgow,G4 0QR','0141225741','Departamento',600);

/*==============================================================*/
/* datos: empleado */
/*==============================================================*/
insert into empleado values('SL21','Jhon','White','Gerente','M','01/10/45',300000,'B005');
insert into empleado values('SG37','Peter','Denver','Asistente','M','10/11/60',120000,'B006');
insert into empleado values('SG14','David','Ford','Supervisor','M','09/09/58',180000,'B003');
insert into empleado values('SA9','Mary','Lee','Asistente','F','17/09/59',90000,'B007');
insert into empleado values('SG5','Susan','Sarandon','Gerente','F','21/03/60',240000,'B003');
insert into empleado values('SL41','Julie','Roberts','Asistente','F','13/06/63',90000,'B005');
insert into empleado values('SL22','Juan','Blanco','Gerente','M','01/10/44',300000,'B005');
insert into empleado values('SG36','Luis','Jara','Asistente','M','10/11/61',120000,'B003');
insert into empleado values('SG13','David','Gates','Supervisor','M','09/09/58',180000,'B003');
insert into empleado values('SA8','Maria','Bombal','Asistente','F','17/09/59',90000,'B007');
insert into empleado values('SG4','Susana','Sarandons','Gerente','F','21/03/60',240000,'B003');
insert into empleado values('SL40','James','Bond','Asistente','F','13/06/63',90000,'B005');
insert into empleado values('SL50','Juan','Perez','Vendedor','M','13/06/63',151000,'B015');
insert into empleado values('SL60','Jaime','Soto','Vendedor','M','14/06/83',350000,'B115');
insert into empleado values('SL70','Julia','Berne','Vendedor','F','23/01/53',200000,'B215');
insert into empleado values('SL55','Jorge','Fernandez','Vendedor','M','13/06/63',151000,'B015');
insert into empleado values('SL65','Jose','Isla','Vendedor','M','14/06/83',350000,'B115');

/*==============================================================*/
/* datos: Propietario */
/*==============================================================*/
insert into propietario values('C046','Joe','Keogh','2 Fergus Dr, AberdeenAB 7SX','0122486121');
insert into propietario values('C087','Carol','Farrel','6 Achray St.Glasgow, G32 9DX','0141357741');
insert into propietario values('C040','Tina','Murphy','63 Well St, Glasgow, G42','0141943742');
insert into propietario values('C093','Tony','Shaw','12 Park PI, Glasgow, G40QR','0141225742');
insert into propietario values('C047','Jose','Casanova','El Volvan 123, Santiago AB 7SX','0122486125');
insert into propietario values('C088','Carolina','Fernandez','Macul 1800. Santiago, G32 9DX','0141357741');
insert into propietario values('C041','Cristina','Mora','Av. Matta 1800, Santiago, G42','0141943752');
insert into propietario values('C094','Tomas','Figueroa','Av. Macul 120, Santiago, G40QR','0141225542');

/*==============================================================*/
/* datos: PROPIEDAD */
/*==============================================================*/
insert into PROPIEDAD values('PA14','16 Holhead','Aberdeem','AB7 5SU','Casa','6','650','C046','SL21');
insert into PROPIEDAD values('PL94','6 Argvill St.','London','NW2','Departamento','4','400','C087','SL21');
insert into PROPIEDAD values('PG4' ,'6 Lawrence St','Glasgow','G119QX','Departamento','3','350','C040','SA9');
insert into PROPIEDAD values('PG36','2 Manor Rd','Glasgow','G114QX','Departamento','3','375','C093','SA9');
insert into PROPIEDAD values('PG21','AV. Matta 150','Santiago','G12','Casa','5','600','C087','SG5' );
insert into PROPIEDAD values('PR01','Macul 120 ','Santaigo','G129AX','Departamento','4','450','C093','SA8');
insert into PROPIEDAD values('PR02','Macul 220','Santiago','G129AX','Departamento','5','550','C093','SG13');
insert into PROPIEDAD values('PR03','Macul 420','Santiago','G129AX','Departamento','6','650','C093','SG14');
insert into PROPIEDAD values('PR04','Macul 620','Santiago','G129AX','Departamento','3','350','C093','SG36');
insert into PROPIEDAD values('PR05','Loa 100','Santiago','G129AX','Departamento','2','250','C093','SG4');
insert into PROPIEDAD values('PG16','Arturo Prats 250','Santiago','G129AX','Departamento','4','450','C047','SL22');
insert into PROPIEDAD values('PR07','Gorbea 200','Santiago','G129AX', 'Departamento','6','650','C047','SL40');
insert into PROPIEDAD values('PR08','Gomez 230','Santiago','G129AX', 'Departamento','2','250','C041','SL41');
insert into PROPIEDAD values('PR09','Garibaldi 1500','Santiago','G129AX', 'Departamento','6','650','C041','SL50');
insert into PROPIEDAD values('PR10','Las Urbinas 210','Santiago','G129AX', 'Departamento','6','650','C094','SL55');
insert into PROPIEDAD values('PR11','Lastarria 1400','Santiago','G129AX', 'Departamento','3','350','C094','SL60');
insert into PROPIEDAD values('PR12','Las Giraldas 200','Santiago','G129AX','Departamento','4','450','C093','SL70');

/*==============================================================*/
/* datos: VISITA */
/*==============================================================*/
insert into visita values('CR56','PA14','24-11-1999','muy pequeño');
insert into visita values('CR62','PA14','14-11-1999','no tiene salón');
insert into visita values('CR76','PG4','20-10-1999','muy lejos');
insert into visita values('CR72','PG16','24-06-2007','Bakan');
insert into visita values('CR72','PG36','24-06-2007','Super');
insert into visita values('CR62','PG16','25-06-2007','Cool');
insert into visita values('CR62','PG4','25-06-2007', NULL);
insert into visita values('CR62','PG36','25-06-2007','No salva');
insert into visita (numCliente, numPropiedad, fecha) values ('CR72','PG4','25-06-2007');
insert into visita (numCliente, numPropiedad, fecha) values('CR56','PG36','28-10-1999');
insert into visita (numCliente, numPropiedad, fecha) values('CR56','PG4','26-11-1999');

/*==============================================================*/
/* datos: ARRIENDO*/
/*==============================================================*/
insert into arriendo values('10024','PA14','CR62','650','Visa','1300','Y','01-06-2005','31-05-2006');
insert into arriendo values('10075','PL94','CR76','400','Contado','800','N','01-08-2005','31-01-2006');
insert into arriendo values('10012','PG21','CR74','600','Cheque','1200','Y','01-07-2005','30-06-2006');
/*==============================================================*/

desc oficina
desc cliente

select numempleado, trim(nombre)||' '||trim(apellido) as "Nombre Apellido", ciudad
from empleado, oficina
where empleado.numoficina = oficina.numoficina

desc empleado
desc oficina


create view empleadoofi as
select numempleado, trim(nombre)||' '||trim(apellido) as "Nombre Apellido", ciudad
from empleado, oficina
where empleado.numoficina = oficina.numoficina

select * from empleadoofi

select ciudad, count(numempleado) as "TOTAL EMPLEADOS"
from EMPLEADOOFI
group by ciudad
having count(numempleado) > 2
order by "TOTAL EMPLEADOS" desc

----
select ciudad, count(numempleado) as "TOTAL EMPLEADOS"
from empleado, oficina
where empleado.numoficina = oficina.numoficina
group by ciudad
having count(numempleado) > 2
order by count(numempleado) desc

select * from empleado

select numempleado, cargo
from empleado
where cargo='Gerente' or cargo='Supervisor' --- siempre poner los nombres igual que el de la base de datos con mayusculas y minusculas

select numempleado, cargo
from empleado
where lower(cargo) in('gerente','supervisor', 'ssistente') -- listar empleados por los siguientes cargos

select numempleado, cargo
from empleado
where lower(cargo) not in('gerente','supervisor', 'asistente')  --- lista empleados que no tengan el cargo indicado en la consulta


-- cuantos empleados tengo por cargo

select cargo, count(numempleado) as "Cantidad de empleados"
from empleado
where lower(cargo) in('gerente','supervisor', 'asistente')  --- lista empleados que no tengan el cargo indicado en la consulta
group by cargo

---cuanto gasto en los siguentes empleados
select trim(cargo) as "cargo", to_char(trim(sum(salario)), '9,999,999')  as "Gasto de dinero por cargo"
from empleado
where lower(cargo) in('gerente','supervisor', 'asistente')  ---
group by cargo

--uso de likees para buscar uns palabra especifica en la consulta
select numcliente, direccion
from cliente
where direccion like '%G4%'

--encontrar las direcciones que empiezan con 5
select numcliente, direccion
from cliente
where direccion like '%G4%'

--encontrar las direcciones que empiezan con h
select numcliente, direccion
from cliente
where trim(direccion) not like '%H%'

desc empleado

---seleccionar todas las vistas que tienen comentarios null
select * from visita
where comentario is null

---seleccionar todas las vistas que tienen comentarios not null
select * from visita
where comentario is not null


---seleccionar el caracter null por un comentario
select numcliente, nvl(comentario, 'no dejo comentarios') from visita
where comentario is null

---ordenar de mayor a menor
select numpropiedad, tipo, hab, renta
from propiedad
group by tipo

-- seleccionar propiedades que cuestan mas de 350 de alquiler
--desc propiedad
select count(numpropiedad) from propiedad
where renta > 350
----
select count(*) from propiedad
where renta > 350
---

--cuantas propiedades se visitaron en noviembre de 1999
select count(numpropiedad) from visita
where fecha >= '01/11/1999' and fecha <= '30/11/1999'

--cuantas distintas hay(visitas a casas diferentes)
select count(distinct numpropiedad) from visita
where fecha >= '01/11/1999' and fecha <= '30/11/1999'

select * from visita
desc propiedad

--listar numero de empleados por oficina de ciudad
select ciudad, count(numempleado) as "numero de empleados", to_char(sum(salario), '9,999,999') as "suma de sueldos"
from oficina, empleado
where oficina.numoficina = empleado.numoficina
group by ciudad

----numero de oficina

select oficina.NUMOFICINA, count(numempleado) as "numero de empleados", to_char(sum(salario), '9,999,999') as "suma de sueldos"
from oficina, empleado
where oficina.numoficina = empleado.numoficina
group by oficina.NUMOFICINA
order by oficina.NUMOFICINA

-- incluir ciudad de oficina y ordebnar por oficina
select trim(oficina.NUMOFICINA)as "NUMERO OFICINA",TRIM(oficina.ciudad) AS "CIUDAD"
, TRIM(count(numempleado)) as "numero de empleados", to_char(sum(salario), '9,999,999') as "suma de sueldos"
from oficina, empleado
where oficina.numoficina = empleado.numoficina
group by oficina.NUMOFICINA, oficina.ciudad
order by oficina.NUMOFICINA



desc empleado

desc oficina

viernes, 15 de marzo de 2013

Trabajo de Funciones

Tarea en clases el 15-03-2013: Sobre funciones:

---ROUND devuelve un valor de numeric_expression redondeado, independientemente del tipo de datos, cuando length es un número negativo.
SELECT ROUND(748.58, -2 )
from dual
----------------------------------------------
----------------------------------------------ROUND siempre devuelve un valor.Si length es un valor negativo y mayor que el número de dígitos anteriores al separador decimal, ROUND devuelve 0.
select round(748.58, -4)
from dual
--------------------------------------------------------------------------------------------
-------------------------------La Funcion Trunc. Si el parámetro es un número devuelve la parte entera.
SELECT TRUNC(9.99)
FROM DUAL;
--------------------------------------------------------------------------------------
---Funcion MOD:-- Devuelve el modulo de dividir 20/15  FROM DUAL
SELECT MOD(20,15)
from dual
-------------------------------------------------------
http://www.devjoker.com/contenidos/articulos/67/Funciones-integradas-de-PLSQL.aspx


-- Uso de funcion to_namber, es para convertit un string a
-- numero usando los siguientes formatos

select to_number('5,540.52','9,999.99')
from dual

select to_number('250','999')
from dual

select to_number('25','99')
from dual

--------------------------------------------------------------------------------

-- el uso de to_char es para dar un valor o formato a un texto o variable

select to_char(51.254,'99.99') -- solo mostraremos dos numeros despues de la coma
from dual

select to_char(sysdate, 'dd') -- en esta opción solo tomaremos el dia de la fecha actual
from dual

- months_between: retorna el numero de meses entre las fechas enviadas como argumento.
Ejemplo:

select months_between('19/05/2003','21/06/05') from dual;-- retorna

-----------------------------------------------------------------------------------------------------------------------------------------------------

- add_months: agrega a una fecha, un número de meses. Si el segundo argumento es positivo, se le suma a la fecha enviada tal cantidad de meses;
si es negativo, se le resta a la fecha enviada tal cantidad de meses.
Ejemplo:

select add_months('10/06/2007',5) from dual; --retorna "10/11/07"

-----------------------------------------------------------------------------------------------------------------------------------------------------
- next_day(fecha,dia): retorna una fecha correspondiente al primer día especificado en "dia" luego de la fecha especificada. En el siguiente ejemplo
se busca el lunes siguiente a la fecha especificada:

select next_day('10/08/2007','LUNES') from dual;

---------------------------------------------------------------------------------------------------------------------------------------------------

- last_day(f): retorna el ultimo día de mes de la fecha enviada como argumento. Ejemplo:

select last_day('10/02/2007') from dual;-- "28/02/07"


url:
http://www.oracleya.com.ar/temarios/descripcion.php?cod=181&punto=23







miércoles, 13 de marzo de 2013

Clase del 13-03-2013

PBD3501: Profesor Erwin Fischer

*create sequence...(Investigar funcion) : seqcliente. Se crea en la base de datos y se almacena en ella, se usa de la siguente manera:
seqcliente.nextval (me dara el valor que corresponde)

create table Cliente(
idCliente integer not null,
nombre varchar2(25)not null,
apellido varchar2(30) not null,
fechaNac date
);  ---Creacion de la tabla
----------------------------------------------------------------
create  sequence sqCliente
start with 10
increment by 10;  --crea secuencia para incrementar
-----------------------------------------------------------
select sqCliente.nextval
from dual;   ---Selecciona la secuencia
---------------------------------------------------------------
alter table Cliente
add  rut varchar(12);  ---Modifica la Tabla y se le agrega un campo
----------------------------------------------------------------
desc Cliente  ---Describe la tabla
-------------------------------------------------------------------
insert into Cliente values (sqCliente.nextval,'Paparatsi', 'Argentino', '24/12/1920', '1-9');
insert into Cliente values(sqCliente.nextval, 'Sepulveda', 'Peruano', '25/10/1992', '6969');
insert into Cliente values(sqCliente.nextval, 'Aceituno', 'Boliviano', '12/04/1992','6965'); ---Insertar Datos
--------------------------------------------------------------------------------------------------------
drop sequence sqCliente;  --Borra la Secuencia
-----------------------------------------------------------------------------------------------
drop table Cliente;  ---Borra la Tabla
--------------------------------------------------------------------------------------------------
select * from Cliente;  ---Consultamos la Tabla
--------------------------------------------------------------------------------------------
select nombre from Cliente;  --Selecciona los nombres de la Tabla
--------------------------------------------------------------------------
select *
from Cliente
where fechaNac >= '01/01/1920'
and fechaNac <= '31/12/1992'  ---Selecciona fechas desde y hasta
----------------------------------------------------------------------------
select *
from Cliente
where fechaNac between '01/01/1920'
and '31/12/1992'
--------------------------------------------------------------------------
select *
from Cliente
where extract (year from fechaNac)=1920
----------------------------------------------------------------------
select extract(year from sysdate) from dual;
-----------------------------------------
select trim (to_char(idCliente))as idCliente, rut, nombre, apellido, to_char(fechaNac, 'dd/mm/yy') as "Fecha de Nacimiento"
from Cliente
where extract (year from fechaNac)=1920