· 6 years ago · Oct 10, 2019, 12:54 AM
1show databases;
2
3/* CREATE crea la base de datos */
4
5CREATE DATABASE `INSTITUTO` DEFAULT CHARACTER SET utf8 COLLATE
6utf8_general_ci;
7
8/* Selecciona la base de datos*/
9USE `INSTITUTO`;
10
11/*CREA TABLA*/
12CREATE TABLE `ALUMNOS`
13(
14
15`NOMBRE` VARCHAR(30) NOT NULL ,
16`APELLIDO` VARCHAR(30) NOT NULL ,
17`DNI` INT NOT NULL ,
18PRIMARY KEY (`DNI`)
19);
20
21select * from ALUMNOS;
22
23/*Instertar datos a una tabla*/
24
25insert into Alumnos (NOMBRE, APELLIDO, DNI) Values ('Juan' , 'Perez' ,'38377146');
26insert into Alumnos (NOMBRE, APELLIDO, DNI) Values ('Carla', 'Gomez' ,'39021022');
27
28select * from CURSOS;
29
30/* Agregar columna a tabla existente*/
31ALTER TABLE `ALUMNOS` ADD `TELEFONO` VARCHAR(10) NOT NULL;
32
33/* Cambiar nombre de columna*/
34ALTER TABLE `ALUMNOS` CHANGE `TELEFONO` `CELULAR` VARCHAR(10) NOT NULL;
35
36/* Eliminar un columna*/
37ALTER TABLE `ALUMNOS` DROP `CELULAR`;
38
39/* Eliminar una tabla*/
40DROP TABLE `CURSOS`;
41
42
43
44 /*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
45
46/* Elimina la base de datos*/
47DROP DATABASE IF EXISTS `LABORATORIO`;
48
49CREATE DATABASE `LABORATORIO`;
50
51USE `LABORATORIO`;
52
53SELECT * FROM `FACTURAS`;
54
55/* NO HACE FALTA LAS COMILLAS SI NO HAY ESPACIOS*/
56
57CREATE TABLE `FACTURAS`
58(
59
60`LETRA` CHAR NOT NULL ,
61`NUMERO` INTEGER NOT NULL ,
62`CLIENTEID` INTEGER NOT NULL ,
63`ARTICULOID` INTEGER NOT NULL ,
64`FECHA` DATE NOT NULL ,
65`MONTO` DOUBLE NOT NULL ,
66PRIMARY KEY (`LETRA` ,`NUMERO`)
67
68);
69
70CREATE TABLE ARTICULOS
71(
72ARTICULOID INT NOT NULL,
73NOMBRE VARCHAR(50) NOT NULL,
74PRECIO DOUBLE NOT NULL,
75STOCK INT NOT NULL,
76PRIMARY KEY (ARTICULOID)
77);
78
79CREATE TABLE CLIENTES
80(
81CLIENTEID INT NOT NULL ,
82NOMBRE VARCHAR(50) ,
83APELLIDO VARCHAR(50) ,
84CUIT CHAR(16) ,
85DIRECCION VARCHAR(50) ,
86COMENTARIOS VARCHAR(50) ,
87PRIMARY KEY (CLIENTEID)
88);
89
90
91insert into facturas(Letra, Numero, ClienteID, ArticuloID, Fecha, Monto) values ('A', 1, 1, 1, '2011/10/18', 500);
92
93insert into facturas(Letra, Numero, ClienteID, ArticuloID, Fecha, Monto) values ('A', 2, 2, 2, '2011/10/18', 2500);
94
95insert into facturas(Letra, Numero, ClienteID, ArticuloID, Fecha, Monto) values ('A', 3, 3, 3, '2011/10/18', 320);
96
97insert into facturas(Letra, Numero, ClienteID, ArticuloID, Fecha, Monto) values ('A', 4, 4, 4, '2011/10/18', 120);
98
99insert into facturas(Letra, Numero, ClienteID, ArticuloID, Fecha, Monto) values ('A', 5, 5, 5, curdate() , 300);
100
101insert into articulos(ArticuloID, Nombre, Precio, Stock) values (1, 'Destornillador', 25, 50);
102
103insert into articulos(ArticuloID, Nombre, Precio, Stock) values (2, 'Pinza' , 35, 22);
104
105insert into articulos(ArticuloID, Nombre, Precio, Stock) values (3, 'Martillo' , 15, 28);
106
107insert into articulos(ArticuloID, Nombre, Precio, Stock) values (4, 'Maza' , 35, 18);
108
109insert into articulos(ArticuloID, Nombre, Precio, Stock) values (5, 'Balde' , 55, 13);
110
111insert into Clientes ( ClienteID, Nombre, Apellido, Cuit, Direccion, Comentarios) values (1, 'Agustin' , 'Diaz' , '20-35987452-0', 'Lima 458' , NULL);
112
113insert into Clientes ( ClienteID, Nombre, Apellido, Cuit, Direccion, Comentarios) values (2, 'Angela' , 'Lopez' , '20-37987854-0', 'Peru 32' , NULL);
114
115insert into Clientes ( ClienteID, Nombre, Apellido, Cuit, Direccion, Comentarios) values (3, 'Cristian', 'Fraga' , '20-36887498-0', 'Chile 6985' , NULL);
116
117insert into Clientes ( ClienteID, Nombre, Apellido, Cuit, Direccion, Comentarios) values (4, 'Sol' , 'Cabral', '20-25982495-0', 'Lavalle 1201', NULL);
118
119insert into Clientes ( ClienteID, Nombre, Apellido, Cuit, Direccion, Comentarios) values (5, 'Ezequiel', 'Perez' , '20-21987111-0', 'Uruguay 25' , NULL);
120
121
122/* Distintos select*/
123
124/* Limitar maximos listados*/
125
126select * from CLIENTES limit 3;
127
128/* Selecciona solo algunas columnas*/
129
130select NOMBRE, APELLIDO, CUIT FROM CLIENTES;
131
132/* Mostrar alguna columnma ordenada*/
133
134select * from CLIENTES order by NOMBRE;
135
136/* Ordenar forma descendiente*/
137
138select * from CLIENTES order by Nombre DESC;
139
140/* Filtrar por un valor = a*/
141
142select * from ARTICULOS where PRECIO=35;
143
144/* Filtrar por un valor Mayor a > o Menor a <* o mayor o igual a <= >=*/
145
146select * from ARTICULOS where PRECIO>35;
147
148select * from ARTICULOS where PRECIO<35;
149
150/* Filtrar por mas de 1 condicion AND o OR*/
151
152select * from ARTICULOS where precio>50 and stock>10; /* precio mayor a 50 y stock mayor a 10 */
153
154select * from ARTICULOS where precio>50 or stock>10; /* precio mayor a 50 O stock mayor a 10*/
155
156select * from ARTICULOS where precio>50 or stock>20 or stock=13; /* precio mayor a 50, stock mayor a 20 O igual a 13 */
157
158select * from FACTURAS where Letra='A' or LETRA='B'; /* filtrando por facutra A o fcatura B */
159
160select * from FACTURAS where LETRA in ('A', 'B');/* Simliar al de arriba */
161
162select * from ARTICULOS where precio>30 and precio< 60; /* Precio entre 30 y 60 */
163
164select * from ARTICULOS where precio between 30 and 60; /* Distinta formas de hacer el mismo de arriba */
165
166select * from ARTICULOS where precio <>100; /* Todos los articulos donde el precio es distinto a 100 */
167
168select * from CLIENTES where NOMBRE= 'Agustin'; /* Campo especifico */
169
170select * from CLIENTES where NOMBRE like'a%'; /* Que empieze con la letra A y termine con cualquiera. El % representa cualq. */
171
172select * from CLIENTES where NOMBRE like '%a'; /* Que termine con la ler A y empieze con cualquiera */
173
174select * from CLIENTES where NOMBRE like '%l%'; /* Que contenga la letra l en cualquier lado */
175
176select * from CLIENTES where NOMBRE like '%l%' and APELLIDO like 'c%'; /* Que contenga una L en cualquier lado y empieze con C */
177
178select * from CLIENTES where (NOMBRE like '%ezequiel%' or nombre like '%sol') and direccion like 'Lavalle%'; /* Que el cliente se llame ezequiel o sol y que si o si la direccion sea Lavalle/*
179
180
181/* LABORATORIO 2 */
182
183/* punto 2 */
184
185select * from ARTICULOS where precio>100;
186select * from ARTICULOS where precio>20 and precio<40;
187select * from ARTICULOS where precio between 40 and 60;
188select * from ARTICULOS where precio=20 and stock>30;
189select * from ARTICULOS where precio=12 or precio=20 or precio=30;
190select * from ARTICULOS where precio in (12, 20 ,30);
191select * from ARTICULOS where precio <>12 or precio <>20 or precio <>30;
192
193/* Punto 3 */
194
195select * from ARTICULOS order by precio DESC, nombre; /* Ordena primero por precio y si hay precios del mismo valor, ordena por nombre*/
196
197select 1 + 1; /* usar sql como calculadora*/
198
199/* PUNTO 4 */
200
201SELECT NOMBRE, PRECIO, PRECIO * 1.21 as PrecioConIVA from ARTICULOS; /* Agrega una columna temporal multiplicando PRECIO x 1.21*/
202
203
204SELECT NOMBRE, PRECIO, PRECIO * 1.21 as PrecioConIVA, Precio -10 as PrecioConDescuento from ARTICULOS; /* Dos columnas temporales, con multiplicacion y suma*/
205
206/* PUNTO 5*/
207
208SELECT NOMBRE, PRECIO, 3 as CANTIDADDECUOTAS, (Precio *0.33) * 1.05 as VALORDECUOTA from ARTICULOS;
209
210
211
212
213/*////////////////////////////////////// Ejerecicios CLASE 3 //////////////////////////////////////////////*/
214
215
216
217
218-- 1- Seleccione todos los registros de la tabla Articulos.
219
220Select * from Articulos;
221
222
223-- 2- Muestre los articulos con precio menor o igual a 50.
224
225select * from Articulos where Precio<=50;
226
227
228-- 3- Seleccione los artículos cuyo precio sea mayor o igual a 500:
229
230select * from Articulos where Precio>=500;
231
232
233-- 4- Seleccione los artículos cuya stock sea menor a 30:
234
235select * from ARticulos where Stock<30;
236
237
238-- 5- Selecciones el nombre y descripción de los artículos que no cuesten $100:
239
240select Nombre, Categoria, Precio from Articulos where Precio <>100;
241
242
243-- 6- Obtenga un listado de los productos que contengan una a.
244
245Select * from Articulos where Nombre like '%a%';
246
247
248-- 7- Obtenga un listado de artículos cuyo precio se encuentre entre 100 y 200 pesos.
249
250Select * From Articulos where Precio between 100 and 200;
251
252
253-- 8 Obtenga un listado de artículos con precio con iva sea menor a 100.
254
255Select Nombre, Precio, (Precio * 1.21) as PrecioConIva from Articulos where (Precio * 1.21)<100;
256
257-- 9 Obtenga un listado de artículos cuyo stock sea menor a 10 y precio con iva mayor a 200.
258
259Select Nombre, Stock, (Precio * 1.21) as PrecioConIva from Articulos where stock<10 and (Precio * 1.21)>200;
260
261-- 10 Obtenga un listado de artículos que pagados en 3 cuotas sin interes, tenga un valor de cuota menor a 50
262
263Select Nombre, (Precio / 3) as ValorDeCuota from Articulos where (Precio / 3)<50;
264
265/* Funciones*/
266
267Select max(Precio) from Articulos; -- maximo valor de una columna
268
269Select min(Precio) From Articulos; -- minimo valor de una columna
270
271Select nombre, max(precio) from Articulos where categoria='Smartphone'; -- Max o min con 1 filtro extra.
272
273Select AVG(precio) from Articulos; -- promedio de una columna
274select round(avg(precio),2) from articulos;-- promedio redondeado a 2 decimales
275
276Select * from clientes where Comentarios is not null; -- Select donde Comentarios no esta vacio.
277Select * from clientes where Comentarios is null; -- Select donde Comentarios esta vacio.
278
279select count(*) from articulos; -- Cuenta todos los campos dentro de una tabla
280select count(*) from articulos where categoria='Smartphone'; -- Cuenta todos los campos de categoria Smartphone
281
282select Categoria, count(*) from articulos group by Categoria; -- Cantidad de veces que aparece cierto valor en una tabla -- GROUP BY --
283
284select sum(stock) from Articulos; -- Suma todos dentro de una columna
285select Categoria, sum(stock) from articulos where categoria='Ferreteria'; -- Suma todo el stock dentro de la categoria "ferreteria"
286
287Select Categoria, sum(stock) from articulos group by Categoria; -- Suma todo el stocks de las ditintas categorias -- GROUP BY --
288Select Categoria, sum(stock) from articulos group by Categoria order by sum(stock); -- ordenado el stock de menor a mayor
289
290select nombre, precio * stock from articulos;
291
292select categoria, (precio * stock) from articulos group by Categoria; -- Todos los resultados de precio x stock de disintas categorias -- GROUP BY --
293
294Select Categoria, sum(stock) from articulos group by Categoria having sum(stock)<50; -- Stocks de distintas categorias, menores a 50. -- HAVING --
295
296select * from clientes;
297
298insert into articulos (ArticuloID, Nombre, Precio, Stock, Categoria) values (14,'iphone 11', 50000, 50, 'Smartphone');
299insert into articulos (ArticuloID, Nombre, Precio, Stock, Categoria) values (15,'iphone 12', 60000, 15, 'Smartphone') ,
300 (16,'s10', 45000, 30, 'smartphone'); -- Agregar mas de 1 valor a la vez con un Insert solo
301
302
303insert into facturas (Letra, Numero, ClienteID, ArticuloID,Fecha, Monto) values ('b', 2, 1, 1 ,'2019/10/02', 5000);
304
305Update Articulos set stock=55 where articuloid=1; -- Actualiza un valor (STOCK) usando el articuloid
306
307update Articulos set stock=stock + 10 where articuloid=2; -- Suma al valor existente (STOCK) 10
308
309update articulos set precio=precio * 1.10; -- Actualiza TODOS los precios por 1.10
310
311update articulos set precio=precio * 1.10 where Categoria='Smartphone'; -- Actualiza todos los precios con un filtor extra
312
313set sql_safe_updates=0; -- Permite modificar todos los campos de una accion sola (saca safe mode)
314
315delete from articulos where articuloid=1; -- Borra un campo (desde arituclo id)
316
317truncate articuls; -- Limpia toda la tabla (borra todo)
318
319select * from facturas where articuloid in
320(select Articuloid from articulos where nombre='Destornillador'); -- Muestra de la tabla facturas, las facutras con el articulo id que tiene el nombre "Destornillador"
321
322select * from articulos where precio in (select max(precio) from articulos); -- Muestra las tablas de articulos donde selecciona el articulo de maximo precio de articulos
323
324
325
326
327
328/* ///////////////////////////////////////// laobratorio 3 UPDATE DELETE //////////////// */
329
330-- 1
331
332insert into Clientes (ClienteID, Nombre, Apellido, Cuit, Direccion) values (6,'Juan','Ricardo',20-45369820-4,'Tucuman 2504'),
333(7, 'Juana','Sanchez',20-64571632-7,'Pasteur 333') ,
334(8, 'Oscar','De la Cruz', 30-4443699-7, 'Sarmiento 2000') ,
335(9, 'Marta','Oliveira', 27-77889901-9, 'Callao 393') ,
336(10,' Luis', 'Rodriguez', 20-16493314-7, 'Yapeyu 1200');
337
338
339select * from clientes where Cuit like '%0';
340
341-- 2
342
343Update clientes set Nombre='Jose' where ClienteID='1';
344
345-- 3
346
347Update clientes set Nombre='Pablo' , Apellido='Fuentes' , Cuit='20-21053119-0' where Clienteid='3';
348
349-- 4
350
351Update clientes set Comentarios=' ' where Comentarios is null;
352
353-- 5
354
355delete from clientes where apellido='Perez';
356
357-- 6
358
359delete from clientes where cuit like '%0';
360
361-- 7
362
363select * from Articulos;
364
365Update articulos set precio= (precio *1.20) where precio<=50;
366
367-- 8
368
369update articulos set precio= (precio * 1.15) where precio>50;
370
371-- 9
372
373update articulos set precio= (precio * 0.95) where precio>200;
374
375-- 10
376
377delete from articulos where stock=0;
378
379
380/* /////////////////////////////////////////////////// LABORATORIO 3 FUNCIONES //////////////////////////////// */
381
382-- 1
383
384Select * from facturas where monto in (select max(monto) from facturas);
385
386-- 2
387
388Select * from facturas where monto in (select min(monto) from facturas);
389
390-- 3
391
392select min(Monto) from facturas where Fecha >='2011/01/01' and Fecha <='2020/12/31';
393
394-- 4
395
396select avg(Monto) from facturas;
397
398-- 5
399
400select avg(Monto) from facturas where Fecha between '2011/01/01' and '2011/12/31';
401
402-- 6
403
404select count(*) from facturas;
405
406-- 7
407
408select count(*) from facturas where monto between '20000' and '50000';
409
410-- 8
411
412select year(Fecha), count(*) from facturas group by Fecha;
413
414-- 9
415
416select year(Fecha), count(*), avg(Monto) from facturas group by Fecha;
417
418-- 10
419
420select Letra, sum(Monto), avg(Monto) from facturas group by Letra;
421
422
423
424/******************************************** CLASE 4 *****************************************/
425
426select * from facturas join clientes; -- Muestra ambas tablas
427
428select * from facturas join clientes on facturas.ClienteId=clientes.Clienteid; -- Muestra ambas tablas unidas por CLIENTE ID --- JOIN Y ON (CUALES Y POR QUE) ---
429
430select * from facturas f join clientes c on f.ClienteId=c.clienteId; -- Asigna el alias "F" para facturas y "c" para clientes solo en este query
431
432select f.letra, f.numero, c.nombre from facturas f join clientes c on f.Clienteid=c.clienteId; -- Pide distintas columnas de diferentes tablas usando alias
433
434select * from facturas f join productos p on f.ArticuloID=p.ArticuloID; -- Ambas tablas unidas por Articulo ID
435
436Select * from facturas f join productos p on f.ArticuloID=p.ArticuloID where p.Categoria='Ferreteria'; -- Ambas tablas, solo categoria ferreteria de PRODUCTOS
437
438Select * from facturas f join productos p on f.ArticuloID=p.Articuloid where p.Categoria='Ferreteria' and f.Monto<=500; -- Ambas tablas, Solo articulos de fereteria de monto 500 o menos
439
440Select max(f.monto) from facturas f join productos p on f.ArticuloID=p.Articuloid where p.Categoria='Ferreteria'; -- Maximo monto, con categoria Ferreteria, de ambas tablas.
441
442Select * from clientes c join facturas f on c.clienteid=f.clienteid
443join productos p on p.articuloid=f.articuloid order by f.letra; -- Junta las 3 tablas, Clientes y facturas por cliente ID y Facturas y producots por Articulo id ordenado por letra de factura
444
445
446/********************************* LABORATORIO CLASE 4 *************************************/
447
448
449-- 1
450
451Select c.nombre, c.apellido from clientes c join facturas f on f.clienteid=c.clienteid;
452
453-- 2
454
455Select distinct c.nombre, c.apellido from clientes c join facturas f on f.clienteid=c.clienteid where f.monto>100; -- DISTINCT no muestra repetidos
456
457-- 3
458
459select f.letra, f.numero, p.nombre, p.precio from facturas f join productos p on f.articuloid=p.articuloid;
460
461-- 4
462
463select max(p.precio), min(p.precio) from facturas f join productos p on p.articuloid=f.articuloid where f.letra='a';
464
465-- 5
466
467select count(*), c.nombre, c.apellido from facturas f join clientes c on f.clienteid=c.clienteid group by c.nombre, c.apellido;
468
469-- 6
470
471select avg(f.articuloid) from facturas f join productos p on f.articuloid=p.articuloid where p.precio>10;
472
473-- 7
474
475select c.nombre, c.apellido, sum(f.monto) from facturas f join clientes c on f.clienteid=c.clienteid group by f.fecha;
476
477
478select * from facturas;