SQL Scripting Test
You have the following tables you are requested to create scripts requested below.
Products Customers Suppliers
-ProductID -CustomerID -SupplierID
-ProductName -CompanyName -CompanyName
-SupplierID -ContactName -ContactName
-CategoryID -ContactTitle -ContactTitle
-QuanityPerUnit -Address -Address
-UnitPrice -City -City
-UnitInStock -Region -Region
-UnitOnOrder -PostalCode -PostalCode
-ReorderLevel -Country -Country
-Discontinued -Phone -Phone
-Fax -Fax
-Homepage
Order Details Orders Categories
-OrderID -OrderID -CategoryID
-ProductID -CustomerID -CategoryName
-UnitPrice -EmployeeID -Description
-Quantity -OrderDate -Picture
-Discount -RequiredDate
-ShippedDate
-ShipVia
-Freight
-ShipName
-ShipAddress
-ShipCity
-ShipRegion
-ShipPostalCode
-ShipCountry
1. Create a script that will return all customer and supplier by city.
ANSWER:
SELECT
'Customer' AS EntityType,
City,
CompanyName,
ContactName,
ContactTitle
FROM Customers
UNION ALL
SELECT
'Supplier' AS EntityType,
City,
CompanyName,
ContactName,
ContactTitle
FROM Suppliers
ORDER BY City, EntityType, CompanyName;
2. Create a script that will match all products to its corresponding categories.
ANSWER:
SELECT
[Link],
[Link],
[Link],
[Link]
FROM Products p
JOIN Categories c ON [Link] = [Link];
3. Create a view that will return the total amount per order of discount. Discount column in
the table is presented in decimal form.
ANSWER:
CREATE VIEW OrderDiscounts AS
SELECT
[Link],
SUM([Link] * [Link] * [Link]) AS TotalDiscount
FROM OrderDetails od
GROUP BY [Link];
4. Create a script that will return if the product is above or below the products average unit price.
ANSWER:
SELECT
[Link],
[Link],
[Link],
CASE
WHEN [Link] > (SELECT AVG(UnitPrice) FROM Products) THEN 'Above Average'
ELSE 'Below Average'
END AS PriceCategory
FROM Products p;
5. Create a view that will summarize the total amount ordered and count unique numbers
of product by customer.
ANSWER:
CREATE VIEW CustomerOrderSummary AS
SELECT
[Link],
[Link],
SUM([Link] * [Link] * (1 - [Link])) AS TotalAmountOrdered,
COUNT(DISTINCT [Link]) AS UniqueProductCount
FROM Orders o
JOIN OrderDetails od ON [Link] = [Link]
JOIN Customers c ON [Link] = [Link]
GROUP BY [Link], [Link];