SQL Ii:: Lab: Application of Selects and Joins
SQL Ii:: Lab: Application of Selects and Joins
As last time:
Download presentation from CULearn to
ensure faster access to queries and ability to
read (especially if youre in the back).
SELECT count(*)
FROM orders
-- Paste this whole screen into SQL Server
and execute (including this line)
SELECT *
FROM orders
inner join [order details]
ON orders.orderid = [order details].orderid
inner join products
ON [order details].productid = products.productid
SELECT *
FROM orders
inner join [order details]
ON orders.orderid = [order details].orderid
inner join products
ON [order details].productid = products.productid
WHERE products.productname = 'chai
NOW: Change this query so that you see only the Company Names of those who bought Chai!
NOW: Change this query so that you can see the Company Names, date, quantities, unitprice, and discount of those who
bought Chai! ORDER by company name
NOW: Change this query so that you know the total price paid for the Chai on each order.
Aliases - example
SELECT
o.orderid
,o.customerid
,c.companyname
,o.shipname AS ShippedToName
FROM
orders o
INNER JOIN
customers c
ON
o.customerid = c.customerid
Now, lets examine an existing view. Go to the views tab under the Northwind
database. Right-click on the view called dbo.Category Sales for 1997. Select top
1000 rows. Then do the same and select design.
SELECT
Customers.CompanyName
,Customers.city
FROM
Customers
ORDER BY Customers.city
Test 1
In Northwind, create a query that outputs
the following three columns:
ProductId
ProductName
Average ordersize
Test 2
Find out how many items Northwind has
sold of each product along with the total
sum for each
Test 2 Answer
SELECT productname,
SUM(quantity) AS NumberOfSales,
SUM((od.unitprice * od.quantity)*
(1 - od.discount)) AS TotalSum
FROM products
INNER JOIN [order details] od
ON od.productid = products.productid
GROUP BY productname
Test 3
Now take the query from Test 2 and
replace the product name with a category
name.
It can be done with two relative simple
changes and an additional join
Test 3 Answer
SELECT
categoryname,
SUM((od.unitprice * od.quantity)* (1 - od.discount)) AS TotalSum,
COUNT(*) AS NumberOfSales
FROM products
INNER JOIN [order details] od
ON od.productid = products.productid
INNER JOIN categories
ON categories.categoryid = products.categoryid
GROUP BY categoryname
14
15
1-5
Note that they dont specify inner, left, right, outer join (which defaults to inner). They also use slightly
different formatting, but youll be fine with what youve learned in class.
Preferred approach: do screenshots into MS Word and crop off everything but the query and the result.