DP080 Lecture 4
DP080 Lecture 4
Module
Agenda Using Subqueries
Exercise 1:
Exercise 2:
Result
Employee Manager
Dan NULL
Aisha Dan
Rosie Dan
Naomi Rosie
Self Joins
Example:
Excersice:
SELECT * FROM…
SELECT * FROM…
Subqueries
In SQL a Subquery can be simply defined as a query within another query
Subqueries can be used with:
• WHERE clause, HAVING clause, FROM clause.
• SELECT, UPDATE, INSERT, DELETE statements,...
Example:
SELECT calendar_year
, calendar_month
FROM
(
SELECT DISTINCT
YEAR(FullDateAlternateKey) as calendar_year
, MONTH(FullDateAlternateKey) as calendar_month
FROM DimDate
) as calendar
Subqueries
Example:
Write a query displaying the Product key, EnglishProductNameName, and Color columns from rows in the
dbo.DimProduct table. Display only those rows in which the SalesAmount exceeded $1,000 and orderdate
during 2010
SELECT Productkey
, EnglishProductNameName
, Color
FROM dbo.DimProduct
where Productkey in
( select Productkey
From FactInternetSales
Where SalesAmount > 1000 )
CTEs - common_table_expression
A common table expression, or CTE, is a temporary named result set created from a simple
SELECT statement that can be used in a subsequent SELECT statement.
Example:
WITH calendar as
(SELECT DISTINCT
YEAR(FullDateAlternateKey) as calendar_year
, MONTH(FullDateAlternateKey) as calendar_month
FROM DimDate)
SELECT calendar_year
, calendar_month
FROM calendar
© Copyright Microsoft Corporation. All rights reserved.