2778A_04

download 2778A_04

of 27

Transcript of 2778A_04

  • 7/31/2019 2778A_04

    1/27

    Module 4:

    Joining Data from MultipleTables

  • 7/31/2019 2778A_04

    2/27

    Module 4: Joining Data from Multiple Tables

    Querying Multiple Tables by Using Joins

    Applying Joins for Typical Reporting Needs

    Combining and Limiting Result Sets

  • 7/31/2019 2778A_04

    3/27

    Lesson 1: Querying Multiple Tables by UsingJoins

    Fundamentals of Joins

    Categorizing Statements by Types of Joins

    Joining Data Using Inner Joins

    Joining Data Using Outer Joins

    Joining Data Using Cross Joins Identifying the Potential Impact of a Cartesian Product

  • 7/31/2019 2778A_04

    4/27

    Fundamentals of Joins

    Select Specific Columns from Multiple Tables

    JOIN keyword specifies that tables are joined and howto join them

    ON keyword specifies join condition

    FROM first_tablejoin_type second_table[ON (join_condition)]

    Joins:

    Simplified JOIN Syntax:

    Query Two or More Tables to Produce a Result Set Use Primary and Foreign Keys as join conditions

    Use columns common to specified tables to join tables

  • 7/31/2019 2778A_04

    5/27

    Categorizing Statements by Types of Joins

    Inner Join

    Includes equi-joins and natural joins

    Use comparison operators to match rows

    Outer Join

    Includes left, right, or full outer joins

    Cross Join

    Also called Cartesian products

    Self Join

    Refers to any join used to join a table to itself

  • 7/31/2019 2778A_04

    6/27

    Joining Data Using Inner Joins

    SELECT e.LoginIDFROM HumanResources.Employee AS e

    INNER JOIN Sales.SalesPerson AS sON e.BusinessEntityID = s.BusinessEntityID

    LoginID-------------------------adventure-works\syed0adventure-works\david8adventure-works\garrett1...(17 row(s) affected)

    An inner join is a join in which the values in the columns

    being joined are compared using a comparison operator

    Result Set:

    Example:

  • 7/31/2019 2778A_04

    7/27

    Joining Data Using Outer Joins

    SELECT p.Name, pr.ProductReviewIDFROM Production.Product pLEFT OUTER JOINProduction.ProductReview prON p.ProductID = pr.ProductID

    Outer Joins return all rows from at least one of the tables

    or views mentioned in the FROM clause

    Name ProductReviewID

    ----------------------------------Adjustable Race NULLBearing Ball NULL...(505 row(s) affected)

    Example:

    Result Set:

  • 7/31/2019 2778A_04

    8/27

    Joining Data Using Cross Joins

    SELECT p.BusinessEntityID, t.Name AS TerritoryFROM Sales.SalesPerson pCROSS JOIN Sales.SalesTerritory tORDER BY p.BusinessEntityID

    In a Cross Join, each row from the left table is combined

    with all rows from the right table

    BusinessEntityID Territory----------------------------274 Northwest274 Northeast

    ...(170 row(s) affected)

    Example:

    Result Set:

    Use CROSS JOINs with caution if you do not need a trueCartesian Product

  • 7/31/2019 2778A_04

    9/27

    Identifying the Potential Impact of a CartesianProduct

    Is defined as all possible combinations of rows in alltables

    A Cartesian Product:

    Results in a rowset containing the number of rows inthe first table times the number of rows in the second

    Can result in huge result sets that take several hoursto complete!

  • 7/31/2019 2778A_04

    10/27

    Demonstration: Querying a Table Using Joins

    In this demonstration, you will see how to:

    Query the Table Using an Inner Join

    Query the Table Using an Outer Join

    Query the Table Using a Cross Join

  • 7/31/2019 2778A_04

    11/27

    Lesson 2: Applying Joins for Typical ReportingNeeds

    Joining Three or More Tables

    Joining a Table to Itself

    Joining Tables by Using Non-Equi Joins

    Joining Tables in a User-Defined Function

  • 7/31/2019 2778A_04

    12/27

    Joining Three or More Tables

    SELECT p.Name, v.NameFROM Production.Product pJOIN Purchasing.ProductVendor pvON p.ProductID = pv.ProductIDJOIN Purchasing.Vendor vON pv.BusinesEntityID = v.BusinessEntityIDWHERE ProductSubcategoryID = 15ORDER BY v.Name

    Example:

    FROM clauses can contain multiple Join specifications

    which allows many tables to be joined in a single Query

    Name Name-----------------------------------------------LL Mountain Seat/Saddle Chicago City SaddlesML Mountain Seat/Saddle Chicago City Saddles...(18 row(s) affected)

    Result Set:

  • 7/31/2019 2778A_04

    13/27

    Joining a Table to Itself

    SELECT DISTINCT pv1.ProductID, pv1.BusinessEntityIDFROM Purchasing.ProductVendor pv1INNER JOIN Purchasing.ProductVendor pv2

    ON pv1.ProductID = pv2.ProductIDAND pv1.BusinessEntityID pv2.BusinessEntityID

    ORDER BY pv1.ProductID

    A Table can be Joined to itself by using a Self-Join

    ProductID BusinessEntityID------------------------------317 1578317 1678...(347 row(s) affected)

    Result Set:

    Example:

  • 7/31/2019 2778A_04

    14/27

    Joining Tables by Using Non-Equi Joins

    SELECT DISTINCT p1.ProductSubcategoryID, p1.ListPriceFROM Production.Product p1

    INNER JOIN Production.Product p2

    ON p1.ProductSubcateogoryID = p2.ProductSubcategoryIDAND p1.ListPrice p2.ListPriceWHERE p1.ListPrice < $15 AND p2.ListPrice < $15ORDER BY ProductSubcategoryID

    The same Operators and Predicates used for Inner Joins

    can be used for Not-Equal Joins

    Example:

    ProductSubcateogoryID ListPrice-----------------------------------23 8.9923 9.50...(8 row(s) affected)

    Result Set:

  • 7/31/2019 2778A_04

    15/27

    SELECT * FROM Sales.ufn_SalesByStore (29825)

    Joining Tables in a User-Defined Function

    CREATE FUNCTION Sales.ufn_SalesByStore (@storeid int)RETURNS TABLE AS RETURN( SELECT P.ProductID, P.Name, SUM(SD.LineTotal)AS 'YTD Total FROM

    Production.Product AS PJOIN Sales.SalesOrderDetail AS SD ONSD.ProductID = P.ProductID

    JOIN Sales.SalesOrderHeader AS SH ONSH.SalesOrderID = SD.SalesOrderID

    WHERE SH.CustomerID = @storeidGROUP BY P.ProductID, P.Name );

    User-defined functions can be used to focus, simplify, and

    customize the perception each user has of the database

    Product ID Name YTD Total------------------------------------------------707 Sport-100 Helmet, Red 620.250910708 Sport-100 Helmet, Black 657.636610

    Example:

    Result Set:

  • 7/31/2019 2778A_04

    16/27

    Demonstration: Joining Tables

    In this demonstration, you will see how to:

    Join Three or More Tables

    Join a Table to Itself

    Join a Table using a Non-Equi Join

  • 7/31/2019 2778A_04

    17/27

    Lesson 3: Combining and Limiting Result Sets

    Combining Result Sets by Using the UNION Operator

    Limiting Result Sets by Using the EXCEPT and INTERSECTOperators

    Identifying the Order of Precedence of UNION, EXCEPT,and INTERSECT

    Limiting Result Sets by Using the TOP and TABLESAMPLEOperators

    Categorizing Statements that Limit Result Sets

    C bi i R lt S t b U i th UNION

  • 7/31/2019 2778A_04

    18/27

    Combining Result Sets by Using the UNIONOperator

    SELECT * FROM testa

    UNION ALLSELECT * FROM testb;

    The number and order of columns must be the same

    in all queries and all data types must be compatible

    UNION combines the results of two or more queries into a

    single result set that includes all the rows that belong toall queries in the union

    Example:

    columna columnb------------------100 test100 test...(8 row(s) affected)

    Result Set:

    Li iti R lt S t b U i th EXCEPT d

  • 7/31/2019 2778A_04

    19/27

    Limiting Result Sets by Using the EXCEPT andINTERSECT Operators

    SELECT ProductID

    FROM Production.ProductEXCEPTSELECT ProductIDFROM Production.WorkOrder

    SELECT ProductIDFROM Production.ProductINTERSECTSELECT ProductIDFROM Production.WorkOrder

    EXCEPT returns any distinct values from the query to the left of theEXCEPT operand that are not also returned from the right query

    INTERSECT returns any distinct values that are returned by boththe query on the left and right sides of the INTERSECT operand

    ProductID

    ------------------429...(266 row(s) affected)

    ProductID------------------3...(238 row(s) affected)

    EXCEPT Example:

    INTERSECT Example:

    Result Sets

    Id tif i th O d f P d f UNION

  • 7/31/2019 2778A_04

    20/27

    Identifying the Order of Precedence of UNION,EXCEPT, and INTERSECT

    EXCEPT, INTERSECT, and UNION are evaluated in the context ofthe following precedence:

    Expressions in parentheses1

    The INTERSECT operand2

    EXCEPT and UNION evaluated from Left to Right based on

    their position in the expression3

    Limiting Result Sets by Using the TOP and

  • 7/31/2019 2778A_04

    21/27

    Limiting Result Sets by Using the TOP andTABLESAMPLE Operators

    TOP and TABLESAMPLE limit the number of rows

    returned in a result set

    SELECT TOP (15)

    FirstName, LastNameFROM Person.Person

    SELECTFirstName, LastName

    FROM Person.PersonTABLESAMPLE (1 PERCENT)

    FirstName LastName--------------------Syed Abbas

    Catherine Abel...(15 row(s) affected)

    FirstName LastName

    --------------------Eduardo BarnesEdward Barnes...(199 row(s) affected)

    TOP Example:

    TABLESAMPLE Example:

    Result Sets

  • 7/31/2019 2778A_04

    22/27

    Categorizing Statements That Limit Result Sets

    UNION

    Combines the results of two or more SELECT statements into asingle result set

    EXCEPT and INTERSECT

    Compares the results of two or more SELECT statements andreturn distinct values

    TOP

    Specifies that only the first set of rows will be returned fromthe query result

    TABLESAMPLE

    Limits the number of rows returned from a table in the FROMclause to a sample number or PERCENT of rows

    Demonstration: Combining and Limiting Result

  • 7/31/2019 2778A_04

    23/27

    Demonstration: Combining and Limiting ResultSets

    In this demonstration, you will see how to:

    Combine Result Sets

    Limit Result Sets using TABLESAMPLE

    Limit Result Sets using TOP

  • 7/31/2019 2778A_04

    24/27

    Lab: Joining Data from Multiple Tables

    Exercise 1: Querying Multiple Tables by Using Joins

    Exercise 2: Applying Joins for Typical Reporting Needs

    Exercise 3: Combining and Limiting Result Sets

    Logon information

    Virtual machine NY-SQL-01User name Administrator

    Password Pa$$w0rd

    Estimated time: 60 minutes

  • 7/31/2019 2778A_04

    25/27

    Lab Scenario

    You are a database developer at Adventure Works. You havebeen asked by the various managers to prepare several reports

    for use in the quarterly financial statements being produced bythe company. To create these reports you will use severaldifferent joins and join operators.

  • 7/31/2019 2778A_04

    26/27

    Lab Review

    What results did the Inner Join in Exercise 1 return?

    What results did the Left Outer Join and Right Outer Joinin Exercise 1 return?

    Why was the ProductVendor table given two different tablealiases in the FROM clause of Exercise 2?

    What would happen if we added an ORDER BY clause tothe TOP select statement in Exercise 3?

  • 7/31/2019 2778A_04

    27/27

    Module Review and Takeaways

    Review Questions

    Best Practices