082 Subqueries

SQL(JOIN效率高)

select *
from Products 
where ProductId = (select top 1 ProductId from OrderLines order by Quantity Desc)

select *
from Products 
where CategoryId in (select CategoryId from Categories where Name != 'Electronics')


select *
from Products p
where (select sum(Quantity) from OrderLines o where o.ProductId = p.ProductId) > 5


SELECT Name as ProductName
FROM Products p
JOIN OrderLines o on p.ProductId=o.ProductId
GROUP BY Name
HAVING SUM(o.Quantity)> 5

SELECT
  p.Name as ProductName,
  c.Name as CategoryName,
(SELECT AVG(p2.Price) FROM Products p2 WHERE p2.CategoryID = c.CategoryID) AS AvgPriceInCategory
FROM Products p
JOIN Categories c ON p.CategoryID=c.CategoryID

猜你喜欢

转载自blog.csdn.net/KevinHuang2088/article/details/143416140