Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Querying with Transact-SQL

Lab 1 – Introduction to Transact-SQL

Overview
In this lab, you will use some basic SELECT queries to retrieve data from the AdventureWorksLT
database.

Challenge 1: Retrieve Customer Data


Adventure Works Cycles sells directly to retailers, who then sell products to consumers. Each retailer
that is an Adventure Works customer has provided a named contact for all communication from
Adventure Works. The sales manager at Adventure Works has asked you to generate some reports
containing details of the company’s customers to support a direct sales campaign.

1. Retrieve customer details


Familiarize yourself with the Customer table by writing a Transact-SQL query that retrieves all columns
for all customers.

Select * from SalesLT.Customer


2. Retrieve customer name data
Create a list of all customer contact names that includes the title, first name, middle name (if any), last
name, and suffix (if any) of all customers.

SELECT Title, FirstName, MiddleName, LastName, Suffix


FROM SalesLT.Customer;
3. Retrieve customer names and phone numbers
Each customer has an assigned salesperson. You must write a query to create a call sheet that lists:
• The salesperson
• A column named CustomerName that displays how the customer contact should be greeted
(for example, “Mr Smith”)
• The customer’s phone number.
SELECT SalesPerson, Title + ' ' + LastName AS CustomerName, Phone
FROM SalesLT.Customer;
Challenge 2: Retrieve Customer and Sales Data
As you continue to work with the Adventure Works customer data, you must create queries for reports
that have been requested by the sales team.

1. Retrieve a list of customer companies


You have been asked to provide a list of all customer companies in the format <Customer ID> :
<Company Name> - for example, 78: Preferred Bikes.

- cast the CustomerID column to a VARCHAR and concatenate with the CompanyName column

SELECT cast(CustomerID AS VARCHAR) + ': ' + CompanyName AS CustomerCompany


FROM SalesLT.Customer;
2. Retrieve a list of sales order revisions
The SalesLT.SalesOrderHeader table contains records of sales orders. You have been asked to retrieve
data for a report that shows:
• The sales order number and revision number in the format <Order Number> (<Revision>) – for
example SO71774 (2).
• The order date converted to ANSI standard format (yyyy.mm.dd – for example 2015.01.31).

SELECT SalesOrderNumber + ' (' + STR(RevisionNumber, 1) + ')' AS OrderRevision,


CONVERT(NVARCHAR(30), OrderDate, 102) AS OrderDate
FROM SalesLT.SalesOrderHeader;

Challenge 3: Retrieve Customer Contact Details


Some records in the database include missing or unknown values that are returned as NULL. You must
create some queries that handle these NULL fields appropriately.

1. Retrieve customer contact names with middle names if known


You have been asked to write a query that returns a list of customer names. The list must consist of a
single field in the format <first name> <last name> (for example Keith Harris) if the middle name is
unknown, or <first name> <middle name> <last name> (for example Jane M. Gates) if a middle name is
stored in the database.

SELECT FirstName + ' ' + ISNULL(MiddleName , ' ') + LastName AS CustomerName


FROM SalesLT.Customer;
2. Retrieve primary contact details
Customers may provide adventure Works with an email address, a phone number, or both. If an email
address is available, then it should be used as the primary contact method; if not, then the phone
number should be used. You must write a query that returns a list of customer IDs in one column, and
a second column named PrimaryContact that contains the email address if known, and otherwise the
phone number.
IMPORTANT: In the sample data provided in AdventureWorksLT, there are no customer records
without an email address. Therefore, to verify that your query works as expected, run the following
UPDATE statement to remove some existing email addresses before creating your query (don’t worry,
you’ll learn about UPDATE statements later in the course).

UPDATE SalesLT.Customer
SET EmailAddress = NULL WHERE CustomerID % 7 = 1;

-- select the CustomerID, and use COALESCE with EmailAddress and Phone columns

SELECT CustomerID, COALESCE(EmailAddress, Phone) AS PrimaryContact


FROM SalesLT.Customer;
3. Retrieve shipping status
You have been asked to create a query that returns a list of sales order IDs and order dates with a
column named ShippingStatus that contains the text “Shipped” for orders with a known ship date, and
“Awaiting Shipment” for orders with no ship date.

IMPORTANT: In the sample data provided in AdventureWorksLT, there are no sales order header
records without a ship date. Therefore, to verify that your query works as expected, run the following
UPDATE statement to remove some existing ship dates before creating your query (don’t worry, you’ll
learn about UPDATE statements later in the course).

UPDATE SalesLT.SalesOrderHeader
SET ShipDate = NULL
WHERE SalesOrderID > 71899;

SELECT SalesOrderID, OrderDate,


CASE
WHEN ShipDate IS NULL THEN 'Awaiting Shipment'
ELSE 'Shipped'
END AS ShippingStatus
FROM SalesLT.SalesOrderHeader;

Next Steps
Well done! You’ve completed the lab, and you’re ready to continue learning about more complex
SELECT query syntax in Module 2 – Querying Tables with SELECT.

Querying with Transact-SQL


Lab 2 – Querying Tables with SELECT
Overview
In this lab, you will use SELECT queries to retrieve, sort, and filter data from the AdventureWorksLT
database.

Challenge 1: Retrieve Data for Transportation Reports


The logistics manager at Adventure Works has asked you to generate some reports containing details
of the company’s customers to help to reduce transportation costs.

1. Retrieve a list of cities


Initially, you need to produce a list of all of you customers' locations. Write a Transact-SQL query that
queries the Address table and retrieves all values for City and StateProvince, removing duplicates.

SELECT Distinct City, StateProvince


FROM SalesLT.Address;
2. Retrieve the heaviest products
Transportation costs are increasing and you need to identify the heaviest products. Retrieve the names
of the top ten percent of products by weight.

-- select the top 10 percent from the Name column

SELECT TOP 10 Percent Name


FROM SalesLT.Product
-- order by the weight in descending order

ORDER BY Weight DESC;


3. Retrieve the heaviest 100 products not including the heaviest ten
The heaviest ten products are transported by a specialist carrier, therefore you need to modify the
previous query to list the heaviest 100 products not including the heaviest ten.

SELECT Name
FROM SalesLT.Product
ORDER BY Weight DESC
-- offset 10 rows and get the next 100

OFFSET 10 ROWS FETCH NEXT 100 ROWS ONLY;

Challenge 2: Retrieve Product Data


The Production Manager at Adventure Works would like you to create some reports listing details of
the products that you sell.
1. Retrieve product details for product model 1
Initially, you need to find the names, colors, and sizes of the products with a product model ID 1.

SELECT Name , Color, Size


FROM SalesLT.Product
-- check ProductModelID is 1

WHERE ProductModelID = 1;
2. Filter products by color and size
Retrieve the product number and name of the products that have a color of 'black', 'red', or 'white' and
a size of 'S' or 'M'.

SELECT ProductNumber, Name


FROM SalesLT.Product
-- check that Color is one of 'Black', 'Red' or 'White'

-- check that Size is one of 'S' or 'M'

WHERE Color IN ('Black', 'Red', 'White') AND Size IN ('S', 'M');


3. Filter products by product number
Retrieve the product number, name, and list price of products whose product number begins 'BK-'.

SELECT ProductNumber, Name, ListPrice


FROM SalesLT.Product
-- filter for product numbers beginning with BK- using LIKE

WHERE ProductNumber LIKE 'BK%';


4. Retrieve specific products by product number
Modify your previous query to retrieve the product number, name, and list price of products whose
product number begins 'BK-' followed by any character other than 'R’, and ends with a '-' followed by
any two numerals.

SELECT ProductNumber, Name, ListPrice


FROM SalesLT.Product
-- filter for ProductNumbers

WHERE ProductNumber LIKE 'BK-[^R]%-[0-9][0-9]';

Next Steps
Well done! You’ve completed the lab, and you’re ready learn how to retrieve data from more than one
table in Module 3 – Querying Multiple Tables with Joins.
Querying with Transact-SQL
Lab 3 – Querying Multiple Tables with Joins

Overview
In this lab, you will use joins to combine data from multiple tables in the AdventureWorksLT database.

Challenge 1: Generate Invoice Reports


Adventure Works Cycles sells directly to retailers, who must be invoiced for their orders. You have
been tasked with writing a query to generate a list of invoices to be sent to customers.

1. Retrieve customer orders


As an initial step towards generating the invoice report, write a query that returns the company name
from the SalesLT.Customer table, and the sales order ID and total due from the
SalesLT.SalesOrderHeader table.
SELECT c.CompanyName, oh.Salesorderid, oh.totaldue
FROM SalesLT.Customer AS c
JOIN SalesLT.SalesOrderHeader AS oh
-- join tables based on CustomerID
ON c.customerid = oh.customerid

2. Retrieve customer orders with addresses


Extend your customer orders query to include the Main Office address for each customer, including
the full street address, city, state or province, postal code, and country or region

Tip: Note that each customer can have multiple addressees in the SalesLT.Address table, so the
database developer has created the SalesLT.CustomerAddress table to enable a many-to-many
relationship between customers and addresses. Your query will need to include both of these tables,
and should filter the join to SalesLT.CustomerAddress so that only Main Office addresses are
included.

SELECT c.CompanyName, a.AddressLine1, ISNULL(a.AddressLine2, '') AS AddressLine2, a.City,


a.StateProvince, a.PostalCode, a.CountryRegion, oh.SalesOrderID, oh.TotalDue
FROM SalesLT.Customer AS c
-- join the SalesOrderHeader table

JOIN SalesLT.SalesOrderHeader AS oh
ON oh.CustomerID = c.CustomerID
-- join the CustomerAddress table

JOIN SalesLT.CustomerAddress AS ca
-- filter for where the AddressType is 'Main Office'

ON c.CustomerID = ca.CustomerID AND AddressType = 'Main Office'


JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID;

Challenge 2: Retrieve Sales Data


As you continue to work with the Adventure Works customer and sales data, you must create queries
for reports that have been requested by the sales team.

1. Retrieve a list of all customers and their orders


The sales manager wants a list of all customer companies and their contacts (first name and last
name), showing the sales order ID and total due for each order they have placed. Customers who
have not placed any orders should be included at the bottom of the list with NULL values for the
order ID and total due.
SELECT c.companyname, c.FirstName, c.LastName, oh.SalesOrderID, oh.TotalDue
FROM SalesLT.Customer AS c
LEFT JOIN SalesLT.SalesOrderHeader AS oh
-- join based on CustomerID
ON c.CustomerID = oh.CustomerID
-- order the SalesOrderIDs from highest to lowest
ORDER By oh.SalesOrderID DESC;

2. Retrieve a list of customers with no address


A sales employee has noticed that Adventure Works does not have address information for all
customers. You must write a query that returns a list of customer IDs, company names, contact
names (first name and last name), and phone numbers for customers with no address stored in the
database.
SELECT c.CompanyName, c.FirstName, c.LastName, c.Phone
FROM SalesLT.Customer AS c
LEFT JOIN SalesLT.CustomerAddress AS ca
-- join based on CustomerID
ON c.CustomerID = ca.CustomerID
-- filter for when the AddressID doesn't exist
WHERE ca.AddressID IS NULL;
3. Retrieve a list of customers and products without orders
Some customers have never placed orders, and some products have never been ordered. Create a
query that returns a column of customer IDs for customers who have never placed an order, and a
column of product IDs for products that have never been ordered. Each row with a customer ID
should have a NULL product ID (because the customer has never ordered a product) and each row
with a product ID should have a NULL customer ID (because the product has never been ordered by a
customer).

SELECT c.CustomerID, p.ProductID


FROM SalesLT.Customer AS c
FULL JOIN SalesLT.SalesOrderHeader AS oh
ON c.CustomerID = oh.CustomerID
FULL JOIN SalesLT.SalesOrderDetail AS od
-- join based on the SalesOrderID

ON od.SalesOrderID = oh.SalesOrderID
FULL JOIN SalesLT.Product AS p
-- join based on the ProductID

ON p.ProductID = od.ProductID
-- filter for nonexistent SalesOrderIDs

WHERE oh.SalesOrderID IS NULL


ORDER BY ProductID, CustomerID;

Querying with Transact-SQL


Lab 4 – Using Set Operators

Challenge 1: Retrieve Customer Addresses


Customers can have two kinds of address: a main office address and a shipping address. The accounts
department want to ensure that the main office address is always used for billing, and have asked
you to write a query that clearly identifies the different types of address for each customer.
1. Retrieve billing addresses
Write a query that retrieves the company name, first line of the street address, city, and a column
named AddressType with the value ‘Billing’ for customers where the address type in the
SalesLT.CustomerAddress table is ‘Main Office’.

SELECT c.CompanyName, a.AddressLine1, a.city, 'Billing' AS AddressType


FROM SalesLT.Customer AS c

JOIN SalesLT.CustomerAddress AS ca
-- join based on CustomerID

ON c.CustomerID = ca.CustomerId
-- join another table

JOIN SalesLT.Address AS a
-- join based on AddressID

ON ca.AddressId = a.AddressId
-- filter for where the correct AddressType

WHERE ca.AddressType = 'Main Office';

2. Retrieve shipping addresses


Write a similar query that retrieves the company name, first line of the street address, city, and a
column named AddressType with the value ‘Shipping’ for customers where the address type in the
SalesLT.CustomerAddress table is ‘Shipping’.

SELECT c.CompanyName, a.AddressLine1, a.City, 'Shipping' AS AddressType


FROM SalesLT.Customer AS c

JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID

JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
-- edit this

WHERE ca.AddressType = 'Shipping';

3. Combine billing and shipping addresses


Combine the results returned by the two queries to create a list of all customer addresses that is
sorted by company name and then address type.
SELECT c.CompanyName, a.AddressLine1, a.City, 'Billing' AS AddressType
FROM SalesLT.Customer AS c

JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID

JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Main Office'
-- edit this as per the instructions

UNION ALL

SELECT c.CompanyName, a.AddressLine1, a.City, 'Shipping' AS AddressType


FROM SalesLT.Customer AS c

JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID

JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Shipping'

ORDER BY c.CompanyName, AddressType;

Challenge 2: Filter Customer Addresses


You have created a master list of all customer addresses, but now you have been asked to create
filtered lists that show which customers have only a main office address, and which customers have
both a main office and a shipping address.

1. Retrieve customers with only a main office address


Write a query that returns the company name of each company that appears in a table of customers
with a ‘Main Office’ address, but not in a table of customers with a ‘Shipping’ address.

SELECT c.CompanyName
FROM SalesLT.Customer AS c
-- join the CustomerAddress table

JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID

JOIN SalesLT.Address AS a
-- join based on AddressID

ON ca.AddressID = a.AddressID
WHERE ca.AddressType = 'Main Office'

EXCEPT

SELECT c.CompanyName
FROM SalesLT.Customer AS c
-- use the appropriate join to join the CustomerAddress table

JOIN SalesLT.CustomerAddress AS ca
-- join based on CustomerID

ON c.CustomerID = ca.CustomerID
-- use the appropriate join to join the Address table

JOIN SalesLT.Address AS a
ON ca.AddressID = a.AddressID
-- filter for the appropriate AddressType

WHERE ca.AddressType = 'Shipping'

ORDER BY c.CompanyName;
2. Retrieve only customers with both a main office address and a shipping address
Write a query that returns the company name of each company that appears in a table of customers
with a ‘Main Office’ address, and also in a table of customers with a ‘Shipping’ address.

-- select the CompanyName column

Select c.CompanyName
-- from the appropriate table

From SalesLT.Customer AS c
-- use the appropriate join with the appropriate table

Join SalesLT.CustomerAddress AS ca
-- join based on CustomerID

ON c.CustomerID = ca.CustomerId
-- use the appropriate join with the appropriate table

JOIN SalesLT.Address AS a
-- join based on AddressID

ON ca.AddressID = a.AddressId
-- filter based on AddressType

where ca.AddressType = 'Main Office'

INTERSECT

-- select the CompanyName column

Select c.CompanyName
FROM SalesLT.Customer AS c
-- use the appropriate join with the appropriate table

join SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID

JOIN SalesLT.Address AS a
-- join based on AddressID

ON ca.AddressID = a.AddressId
-- filter based on AddressType

where ca.AddressType = 'Shipping'

ORDER BY c.CompanyName;

You might also like