SlideShare una empresa de Scribd logo
1 de 2
PRACTICA CALIFICADA                                                      ULADECH

                              Sesion: Subconsultas

Una subconsulta es una sentencia SELECT que aparece dentro de otra
sentencia SELECT. Normalmente se utilizan para filtrar una clausula WHERE o
HAVING con el conjunto de resultados de la subconsulta, aunque tambien
pueden utilizarse en la lista de selección.

Por ejemplo podriamos consultar el alquiler ultimo de un cliente:

      SELECT CO_CLIENTE, NOMBRE, MARCA, MODELO
      FROM ALQUILERES
      WHERE CO_CLIENTE = 1
      AND    FECHA_ALQUILER = (SELECT MAX (FECHA_ALQUIER)
            FROM ALQUILERES
           WHERE CO_CLIENTE = 1)

En este caso, la subconsulta se ejecuta en primer lugar, obteniendo el valor de
la maxima fecha de alquiler, y posteriormente se obtienen los datos de la
consulta principal.    Una subconsulta tiene la misma sintaxis que una
sentencia SELECT normal exceptuando que aparece encerrada entre
parentesis.       La subconsulta se puede encontrar en la lista de selección, en
la clausula WHERE o en la clausula HAVING de la consulta principal.

Tiene las siguientes restricciones:

•No puede contener la clausula ORDER BY
•No puede ser la UNION de varias sentencias SELECT
•Si la subconsulta aparece en la lista de selección o esta asociada a un
operador igual “=” solo puede devolver un unico registro.

En el proceso de trabajko con subconsultas, necesariamente manejaremos dos
tipos de consultas: consultas internas y consultas externas. Las consultas
internas no es mas que las subconsultas propiamente dichas y la consulta
externa es aquella que hace uso de los resultados devueltos por las consulta
interna o subconsulta. En todo este rollo, tambien se haran uso del predicado
IN. La consulta externa usa elpredicado IN para operar con los valores
devueltos por la subconsulta. Ejemplo:

      --lista los campos ProductID, ProductName, UnitsInStock,UnitPrice de todos
      --los productos vendidos en una cantidad mayor e igual a 100
      SELECT ProdctId, ProductName, UnitsInStock, UnitPrice
      FROM Products
      WHERE ProductID IN
                           ( SELECT ProductID
                             FROM (ORDER DETAILS)
                             WHERE Quantity>=100 ) ORDER BY productName


ROBERTO CAMPOS DIAZ
PRACTICA CALIFICADA                                                                      ULADECH

                                EJEMPLOS DE TABLAS

                 LUNES          MARTES             MIERCOLES             JUEVES         VIERNES
   9 A 10       LENGUA       NATURALEZA               LENGUA           NATURALEZA       LENGUA
   10 A 11     MATEMATICA      SOCIALES         MATEMATICA              SOCIALES       MATEMATICA
                   S                                S                                      S
  11 A 11.30    RECREO          RECREO                RECREO             RECREO         RECREO
  11.30 A 13     INGLES             INGLES          SOCIALES             INGLES        NATURALEZA



               CASA         COCHE            OCIO             AGUA            LUZ          GAS
  ENERO        112 $         28 $            2300 $             68 $         45,34 $      112,23 $
 FEBRERO       125 $         45 $             0$                30 $           34 $       145,23 $
 MARZO         154 $         56 $            1000 $             35 $         34,56 $      89,34 $



  Nombre        Codpedido      fechapedido         requerimiento        Totalpedido    codproveedor
     de
  columna
  Tipo key         PK                                                                      FK
   Nulos           NN                NN                NN                  NN              NN
  ejemplos        D001          14/06/10              Pintura             300.00           #01
                  D002          31/06/10              Alicate            1390.00           #02
                  D004          15/07/10               Codo               595.00           #04




ROBERTO CAMPOS DIAZ

Más contenido relacionado

Último

Modulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdfModulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdf
AnnimoUno1
 

Último (11)

pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNIT
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
 
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptxPROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
 
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdfRefrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
Refrigerador_Inverter_Samsung_Curso_y_Manual_de_Servicio_Español.pdf
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estos
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.
 
Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvana
 
Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21
 
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptxEL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
 
Modulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdfModulo-Mini Cargador.................pdf
Modulo-Mini Cargador.................pdf
 

Destacado

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destacado (20)

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

Practica calificada campos diaz roberto

  • 1. PRACTICA CALIFICADA ULADECH Sesion: Subconsultas Una subconsulta es una sentencia SELECT que aparece dentro de otra sentencia SELECT. Normalmente se utilizan para filtrar una clausula WHERE o HAVING con el conjunto de resultados de la subconsulta, aunque tambien pueden utilizarse en la lista de selección. Por ejemplo podriamos consultar el alquiler ultimo de un cliente: SELECT CO_CLIENTE, NOMBRE, MARCA, MODELO FROM ALQUILERES WHERE CO_CLIENTE = 1 AND FECHA_ALQUILER = (SELECT MAX (FECHA_ALQUIER) FROM ALQUILERES WHERE CO_CLIENTE = 1) En este caso, la subconsulta se ejecuta en primer lugar, obteniendo el valor de la maxima fecha de alquiler, y posteriormente se obtienen los datos de la consulta principal. Una subconsulta tiene la misma sintaxis que una sentencia SELECT normal exceptuando que aparece encerrada entre parentesis. La subconsulta se puede encontrar en la lista de selección, en la clausula WHERE o en la clausula HAVING de la consulta principal. Tiene las siguientes restricciones: •No puede contener la clausula ORDER BY •No puede ser la UNION de varias sentencias SELECT •Si la subconsulta aparece en la lista de selección o esta asociada a un operador igual “=” solo puede devolver un unico registro. En el proceso de trabajko con subconsultas, necesariamente manejaremos dos tipos de consultas: consultas internas y consultas externas. Las consultas internas no es mas que las subconsultas propiamente dichas y la consulta externa es aquella que hace uso de los resultados devueltos por las consulta interna o subconsulta. En todo este rollo, tambien se haran uso del predicado IN. La consulta externa usa elpredicado IN para operar con los valores devueltos por la subconsulta. Ejemplo: --lista los campos ProductID, ProductName, UnitsInStock,UnitPrice de todos --los productos vendidos en una cantidad mayor e igual a 100 SELECT ProdctId, ProductName, UnitsInStock, UnitPrice FROM Products WHERE ProductID IN ( SELECT ProductID FROM (ORDER DETAILS) WHERE Quantity>=100 ) ORDER BY productName ROBERTO CAMPOS DIAZ
  • 2. PRACTICA CALIFICADA ULADECH EJEMPLOS DE TABLAS LUNES MARTES MIERCOLES JUEVES VIERNES 9 A 10 LENGUA NATURALEZA LENGUA NATURALEZA LENGUA 10 A 11 MATEMATICA SOCIALES MATEMATICA SOCIALES MATEMATICA S S S 11 A 11.30 RECREO RECREO RECREO RECREO RECREO 11.30 A 13 INGLES INGLES SOCIALES INGLES NATURALEZA CASA COCHE OCIO AGUA LUZ GAS ENERO 112 $ 28 $ 2300 $ 68 $ 45,34 $ 112,23 $ FEBRERO 125 $ 45 $ 0$ 30 $ 34 $ 145,23 $ MARZO 154 $ 56 $ 1000 $ 35 $ 34,56 $ 89,34 $ Nombre Codpedido fechapedido requerimiento Totalpedido codproveedor de columna Tipo key PK FK Nulos NN NN NN NN NN ejemplos D001 14/06/10 Pintura 300.00 #01 D002 31/06/10 Alicate 1390.00 #02 D004 15/07/10 Codo 595.00 #04 ROBERTO CAMPOS DIAZ