Rob Gleasure R.Gleasure@ucc.ie robgleasure.com IS6126 Databases for Management Information Systems Lecture 4: SQL IV – Solution Rob Gleasure R.Gleasure@ucc.ie robgleasure.com
Exercise Consider the following problems, what queries best solve them? We want to select the average Quantity for each ProductID in the OrderDetails table? SELECT OrderDetails.ProductID,AVG(OrderDetails.Quantity) AS AverageQuantity FROM OrderDetails GROUP BY OrderDetails.ProductID; We want to create the same result but with the ProductName from the Products table instead of the ProductID (Hint – use LEFT JOIN)? SELECT Products.ProductName,AVG(OrderDetails.Quantity) AS AverageQuantity FROM OrderDetails LEFT JOIN Products ON Products.ProductID=OrderDetails.ProductID GROUP BY Products.ProductName;
Exercise We want to create the same result but with the AverageQuantity rounded to two decimal places? SELECT Products.ProductName,ROUND(AVG(OrderDetails.Quantity),2) AS AverageQuantity FROM OrderDetails LEFT JOIN Products ON Products.ProductID=OrderDetails.ProductID GROUP BY Products.ProductName; We want the same result but displayed according to the first three letters of the ProductName in upper case, e.g. SELECT UCASE(MID(Products.ProductName,1,3)) AS CompanyAbbrev, ROUND(AVG(OrderDetails.Quantity),2) AS AverageQuantity FROM OrderDetails CompanyAbbrev AverageQuantity ALI 30.09 ANI 40