Vous êtes sur la page 1sur 24

Student Lab Manual

T-SQL for SQL Server

1
Introduction:

This lab manual is based on the SQL Server 2005 AdventureWorks sample database.

All assignments will use the objects from the AdventureWorks database, and the labs will use the
Microsoft SQL Server management Studio as a learning platform.

Each lab will feature a basic assignment and optionally a challenge assignment. You Instructor will
review each lab in class and provide example solutions to the challenge assignments.

Learning SQL is a hand-on experience, you are encouraged to explore beyond these basic assignments
and ask questions in class.

Before you proceed beyond a specific lab, please ensure you understand the topics being explored and
all your questions have been answered.

Enjoy and have fun.

2
Lab 1: Learning to explore a Database Table in SQL Server Management Studio

For the Employee table in the AdventureWorks sample database, please answer the following
questions:

1. What is the Schema the Employee table belongs in?

2. What is the Primary Key for the Employee table?

3. Are there any Foreign Keys within the Employee table, if so what tables do these keys
reference?

4. Which field(s) of the Employee table may be null?

5. What are the valid entries in the MartialStatus column?

6. Which field(s) hold variable length data?

7. What is the Default Value for the SalariedFlag? And what does it mean?

Lab 1 Challenge:

Examine the uEmplyee Trigger and answer the following question:

1. Which field(s) will change value when the uEmployee Trigger is invoked?

3
Lab 2: Using the Graphical Query Designer

Using the Graphical Query Designer, add the following tables and fields:

Contact (Table)
FirstName (Field)
LastName
Employee
Title
SalesPerson
SalesYTD
SalesTerritory
Name
CountryRegion
Name

Run the Query and examine the results.

Lab 2 Challenge:

Can you design a query to produce the following results?

A listing of all products that includes:

Product name, Name of the Vendor that supplies that product and the City that Vendor is located in?

4
Lab 3: The Languages of SQL

SQL has three sub-languages:


Data Manipulation Language (DML)
Data Definition Language (DDL)
Data Control Language (DCL)

Please match the SQL command with the sub-language it belongs in:

Command DML DDL DCL

Select
Alter
Grant
Update
Deny
Create
Drop
Delete
Deny
Insert

Lab 3 Challenge:

To add a column to an existing database table, which of the command listed above would be required
to:

Define the security rules to change the table?

Make the change to the table?

Add content to existing rows in the table?

5
Lab 4: The Select Command

For the Employee table in the AdventureWorks sample database, please create the following queries:

1. All the records in the Employee table.

2. A list of: Employee Login IDs, Titles, and Vacation Hours.

3. All non-married Employees.

4. All married male Employees.

5. All Employees sorted by Hire Date.

Lab 4 Challenge:

Create a query that lists: All Employees that have no manager, sorted by title and birth date

6
Lab 5: The Select Command Comparison Operators

For the Production.Product table in the AdventureWorks sample database, please create the following
queries:

1. All Products that are 'Black' in Color.

2. All Products that have a Safety Stock Level less than 100.

3. All Products that have a Product Number starting with 'BK'.

4. All Products that have the word 'Lock in their name.

5. Product Name, Color and Size where the Size is Not 'L' or Not 'M' or not null.

Lab 5 Challenge:

Create a query to list: Product Name, Number, Days to Manufacture, and List Price for all Products that
take between 3 and 6 days to manufacture, sorted by list price in descending order.

7
Lab 6: The Select Command Expanded Filtering

For the Sales.SalesPerson table in the AdventureWorks sample database, please create the following
queries:

1. All records that have a Bonus between 1000.00 and 5000.00 sort by Bonus.

2. All records for Territories 1, 2 and 4;

3. First 10 records.

4. All record where this years sales is greater than last years sales.

5. All records with nulls in Territory ID sorted by Sales Person Id in descending order.

Lab 6 Challenge:

Create a query to list: The top 25 percent of sales where last years sales was not zero.

8
Lab 7: The SQL Functions

These question refer to several tables in the AdventureWorks sample database, please create the
following queries:

1. The average commission percent for the SalesPerson table.

2. A count of all Male Employees;

3. The highest List Price of any Product.

4. The length of all Descriptions in the ProductDescription table.

5. The Currency Code and the first 3 letters of the Currency Name as 'AB'.

Lab 7 Challenge:

Create query to list the number of days between the Product Sell Start Date and the Product Sell End
Date, where Sell End Date is a valid date.

9
Lab 8: The Aggregation and Grouping

These question refer to several tables in the AdventureWorks sample database, please create the
following queries:

1. List the Title, Gender, and Lowest Login Id for each group of Employees grouped by the
following titles: Buyer', 'Recruiter' or 'Stocker'.

2. List Product Sub Category IDs from the Product table, include only those subcategories that
occur more than 20 times. In addition to the ID also return the first product name in
alphabetical order and the highest price for products in this subcategory.

3. Provide a list of Employee Titles and Genders from the Employee table. For each title, include
the average vacation hours for all employees of each gender. Also provide an additional subtotal
for each title that includes the average vacation hours for all employees of that title.

Lab 8 Challenge:

Create query to list the number of Employees for each Manager.

10
Lab 9: The Multi-Table Queries

These question refer to several tables in the AdventureWorks sample database, please create the
following queries:

1. Create a list of Vendors and the subtotals amounts for their purchase orders, sorted by vendor
name. Please include vendor name, and the subtotal amount for all vendors who have purchase
orders recorded in the PurchaseOrderHeader table.

2. Provide a list of all Product subcategories and related products that do not have any sales order
detail records. Please provide two columns including the SubCategory Name and the Product
Name.

Lab 9 Challenge:

Create query to list the all Managers by name.

11
Student Lab Manual

T-SQL for SQL Server

Solutions

12
Lab 1: Learning to explore a Database Table in SQL Server Management Studio

For the Employee table in the AdventureWorks sample database, please answer the following
questions:

1. What is the Schema the Employee table belongs in?

HumanResources

2. What is the Primary Key for the Employee table?

EmployeeID

3. Are there any Foreign Keys within the Employee table, if so what tables do these keys
reference?

ContactID Contact
ManagerID Employee

4. Which field(s) of the Employee table may be null?

ManagerID

5. What are the valid entries in the MartialStatus column?

M = Married, S = Single

6. Which field(s) hold variable length data?

NationalIDNumber,
LoginID
Title

7. What is the Default Value for the SalariedFlag? And what does it mean?

((1)) Job classification.


0 = Hourly, not exempt from collective bargaining.
1 = Salaried, exempt from collective bargaining.

13
Lab 2: Using the Graphical Query Designer

Using the Graphical Query Designer, add the following tables and fields:

Contact (Table)
FirstName (Field)
LastName
Employee
Title
SalesPerson
SalesYTD
SalesTerritory
Name
CountryRegion
Name

Run the Query and examine the results.

14
Lab 3: The Languages of SQL

SQL has three sub-languages:


Data Manipulation Language (DML)
Data Definition Language (DDL)
Data Control Language (DCL)

Please match the SQL command with the sub-language it belongs in:

Command DML DDL DCL

Select X
Alter X
Grant X
Update X

15
Deny X
Create X
Drop X
Delete X
Deny X
Insert X

16
Lab 4: The Select Command

For the Employee table in the AdventureWorks sample database, please create the following queries:

1. All the records in the Employee table.

SELECT * FROM HumanResources.Employee;

2. A list of: Employee Login IDs, Titles, and Vacation Hours.

SELECT LoginID, Title, VacationHours


FROM HumanResources.Employee;

3. All non-married Employees.

SELECT *
FROM HumanResources.Employee
WHERE MaritalStatus = 'S';

4. All married male Employees.

SELECT *
FROM HumanResources.Employee
WHERE MaritalStatus = 'M'
AND Gender = 'M';

5. All Employees sorted by Hire Date.

SELECT *
FROM HumanResources.Employee
ORDER BY HireDate;

17
Lab 5: The Select Command Comparison Operators

For the Production.Product table in the AdventureWorks sample database, please create the following
queries:

1. All Products that are 'Black' in Color.

SELECT *
FROM Production.Product
WHERE Color = 'Black';

2. All Products that have a Safety Stock Level less than 100.

SELECT *
FROM Production.Product
WHERE SafetyStockLevel < 100;

3. All Products that have a Product Number starting with 'BK'.

SELECT *
FROM Production.Product
WHERE ProductNumber LIKE 'BK%';

4. All Products that have the word 'Lock in their name.

SELECT *
FROM Production.Product
WHERE Name LIKE '%Lock%';

5. Product Name, Color and Size where the Size is Not 'L' or Not 'M' or not null.

SELECT Name, Color, Size


FROM Production.Product
WHERE Size != 'L' OR
Size != 'M' OR
Size IS NOT NULL;

18
Lab 6: The Select Command Expanded Filtering

For the Sales.SalesPerson table in the AdventureWorks sample database, please create the following
queries:

1. All records that have a Bonus between 1000.00 and 5000.00 sort by Bonus.

SELECT *
FROM Sales.SalesPerson
WHERE Bonus BETWEEN 1000.00 AND 5000.00
ORDER BY Bonus;

2. All records for Territories 1, 2 and 4;

SELECT *
FROM Sales.SalesPerson
WHERE TerritoryID IN (1,2,4);

3. First 10 records.

SELECT TOP 10 *
FROM Sales.SalesPerson;

4. All record where this years sales is greater than last years sales.

SELECT *
FROM Sales.SalesPerson
WHERE SalesYTD > SalesLastYear;

5. All records with nulls in Territory ID sorted by Sales Person Id in descending order.

SELECT *
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL
ORDER BY SalesPersonID DESC;

19
Lab 7: The SQL Functions

These question refer to several tables in the AdventureWorks sample database, please create the
following queries:

1. The average commission percent for the SalesPerson table.

SELECT AVG(CommissionPct)
FROM Sales.SalesPerson;

2. A count of all Male Employees;

SELECT COUNT(*)
FROM HumanResources.Employee
WHERE Gender = 'M';

3. The highest List Price of any Product.

SELECT MAX(ListPrice)
FROM Production.Product;

4. The length of all Descriptions in the ProductDescription table.

SELECT LEN(Description)
FROM Production.ProductDescription;

5. The Currency Code and the first 3 letters of the Currency Name as 'AB'.

SELECT CurrencyCode, LEFT(Name, 3) AS AB


FROM Sales.Currency;

20
Lab 8: The Aggregation and Grouping

These question refer to several tables in the AdventureWorks sample database, please create the
following queries:

1. List the Title, Gender, and Lowest Login Id for each group of Employees grouped by the
following titles: Buyer', 'Recruiter' or 'Stocker'.

SELECT Title, MIN(LoginID) AS Login


FROM HumanResources.Employee
WHERE Title IN('Buyer', 'Recruiter' , 'Stocker')
GROUP BY Title;

2. List Product Sub Category IDs from the Product table, include only those subcategories that
occur more than 20 times. In addition to the ID also return the first product name in
alphabetical order and the highest price for products in this subcategory.

SELECT ProductSubCategoryID, MIN(Name) AS Name, MAX(ListPrice)


FROM Production.Product
GROUP BY ProductSubCategoryID
HAVING COUNT(ProductSubCategoryID) > 20
ORDER BY Name;

3. Provide a list of Employee Titles and Genders from the Employee table. For each title, include
the average vacation hours for all employees of each gender. Also provide an additional subtotal
for each title that includes the average vacation hours for all employees of that title.

SELECT Title, Gender, AVG(VacationHours)


FROM HumanResources.Employee
GROUP BY Title, Gender
WITH ROLLUP;

21
Lab 9: The Multi-Table Queries

These question refer to several tables in the AdventureWorks sample database, please create the
following queries:

1. Create a list of Vendors and the subtotals amounts for their purchase orders, sorted by vendor
name. Please include vendor name, and the subtotal amount for all vendors who have purchase
orders recorded in the PurchaseOrderHeader table.

SELECT Name, SubTotal


FROM Purchasing.Vendor INNER JOIN Purchasing.PurchaseOrderHeader
On Vendor.VendorID = PurchaseOrderHeader.VendorID
ORDER BY Name;

2. Provide a list of all Product subcategories and related products that do not have any sales order
detail records. Please provide two columns including the SubCategory Name and the Product
Name.

SELECT ProductSubCategory.Name AS SubCategory,


Product.Name AS ProductName
FROM Production.ProductSubCategory INNER JOIN Production.Product
ON Production.ProductSubCategory.ProductSubCategoryID =
Product.ProductSubCategoryID
LEFT OUTER JOIN Sales.SalesOrderDetail
ON Product.ProductID = Sales.SalesOrderDetail.ProductID
WHERE SalesOrderDetail.ProductID IS NOT NULL;

22
Challenge

Lab 1:

UPDATE [HumanResources].[Employee]
SET [HumanResources].[Employee].[ModifiedDate] = GETDATE()

Lab 2:

SELECT Purchasing.Vendor.Name, Production.Product.Name AS Vendor, Person.Address.City


FROM Purchasing.VendorAddress INNER JOIN
Purchasing.Vendor ON Purchasing.VendorAddress.VendorID =
Purchasing.Vendor.VendorID INNER JOIN
Purchasing.ProductVendor ON Purchasing.Vendor.VendorID =
Purchasing.ProductVendor.VendorID INNER JOIN
Production.Product ON Purchasing.ProductVendor.ProductID =
Production.Product.ProductID INNER JOIN
Person.Address ON Purchasing.VendorAddress.AddressID = Person.Address.AddressID

Lab 3:

Define Security Rules: GRANT


Make changes to Table: ALTER
Add Content to Exiting Rows: UPDATE

Lab 4:

SELECT *
FROM HumanResources.Employee
WHERE ManagerID IS NULL
ORDER BY Title, BirthDate

Lab 5:

SELECT Name, ProductNumber, DaysToManufacture, ListPrice


FROM Production.Product
WHERE DaysToManufacture BETWEEN 3 AND 6
ORDER BY ListPrice DESC

23
Lab 6:

SELECT TOP 25 PERCENT *


FROM Sales.SalesPerson
WHERE NOT SalesLastYear = 0.0

Lab 7:

SELECT Name, DATEDIFF(day, SellStartDate, SellEndDate) AS [Days for Sell]


FROM Production.Product
WHERE SellEndDate IS NOT NULL

Lab 7:

SELECT Name, DATEDIFF(day, SellStartDate, SellEndDate) AS [Days For Sale]


FROM Production.Product
WHERE SellEndDate IS NOT NULL
ORDER BY [Days For Sale]

Lab 8:

SELECT ManagerID, COUNT(*) AS [Employee Count]


FROM HumanResources.Employee
WHERE ManagerID IS NOT NULL
GROUP BY ManagerID
ORDER BY [Employee Count]

Lab 9:

SELECT C.FirstName + ' ' + C.LastName AS [Manager Name]


FROM HumanResources.Employee AS E1, Person.Contact AS C
WHERE E1.ContactID = C.ContactID
AND E1.EmployeeID IN (
SELECT DISTINCT ManagerID
FROM HumanResources.Employee
WHERE ManagerID IS NOT NULL
)
ORDER BY [Manager Name]

24

Vous aimerez peut-être aussi