Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
USE northwind
SELECT orderid, customerid
FROM orders
GO
LA SUBCONSULTA QUEDARIA
USE northwind
SELECT T.orderid, T.customerid
FROM ( SELECT orderid, customerid
FROM orders ) AS T
GO
1. De acuerdo con su analisis concluya cuál seria el objetivo de realizar
subconsultas como una tabla derivada y en que caso usted la
utilizaria, escriba un ejemplo para hacerlo.
R//
Utilizando la subConsulta es una forma de acceder a lo que se solicta de
una manera directamente y correcta ya que en la consulta normal no
siempre acceder a ciertos datos sera simple o correctos!
USE northwind
select ProductName, UnitPrice, avg (UnitPrice)as precioProm, unitprice- avg
(UnitPrice)as diferencia
from Products
where CategoryID = 6
group by ProductName, UnitPrice
GO
USE northwind
select ProductName, UnitPrice, (select avg(UnitPrice) from Products) as
PrecioPromedio,
UnitPrice -(select AVG(UnitPrice)from Products) as diferencia
from products
where CategoryID = 6
GO
2. Describa con sus propias palabras cual es la diferencia entre las
consultas y por qué deberiamos involucrar una subconsulta para
obtener el resultado deseado.
USE northwind
SELECT od.orderid, customerid
FROM orders AS or1 inner join [order details] AS od on or1.OrderID=od.OrderID
where Quantity > 20 and od.ProductID = 23
GO
LA SUBCONSULTA QUEDARIA
USE northwind
SELECT orderid, customerid
FROM orders AS or1
WHERE 20 < (SELECT quantity FROM [order details] AS od
WHERE or1.orderid = od.orderid AND od.productid = 23)
GO
USE northwind
SELECT orderid, customerid
FROM orders AS or1
WHERE (SELECT quantity FROM [order details] AS od
WHERE or1.orderid = od.orderid AND od.productid = 23)>20
GO
R//
Esta dando la condicion de que el atributo OrderId esta en la tabla de la
consulta al igual que en la tabla de la subconsulta igualando el atributo
OrderId de la tabla de la consulta con el de la tabla de la subconsulta asi
cumpliendo la condicional anterior
USE northwind
SELECT od.orderid, customerid
FROM orders AS or1 inner join [order details] AS od on or1.OrderID=od.OrderID
where Quantity > 20 and od.ProductID = 23
GO
R//
Implemente la primera ya que solo era mas facil hacer una subconulta
mostrandol; sentenciandola en el select de la consulta normal
use Northwind
select distinct od.ProductID
from [Order Details] od
where od.ProductID in (select od.ProductID from [Order Details] ods
where od.UnitPrice <> ods.UnitPrice) group by od.ProductID having
COUNT(od.ProductID) > 20
order by od.ProductID
r// 1
Cuál es la parte de la sintaxis que corresponde a la subconsulta.
__________________________________________________.
use Northwind
select distinct od.ProductID , ProductName
from [Order Details] od inner join dbo.Products Pro on od.ProductID=
Pro.ProductID
where od.ProductID in (select od.ProductID from [Order Details] ods
where od.UnitPrice <> ods.UnitPrice) group by od.ProductID , ProductName
having COUNT(od.ProductID) > 20
order by od.ProductID ,ProductName