SlideShare une entreprise Scribd logo
1  sur  55
SQL302




              Intermediate SQL Programming
   Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T-
   SQL Fundamentals by Itzki Ben-gan

            Workshop 2 – Joins, Set Operations, Window
                            Functions
Bookstore                         SQL302 Module 2                                 1
Note on SQL302 Slides
    • These slides were originally designed to support a
      single SQL course which was used for any of MS
      Access, MySQL, Oracle and SQL Server.
    • As such you may see here slides developed in any
      one of the above products.
    • We are in the process of migrating the Oracle,
      Access, and MySQL slides out into their own slide
      sets. The SQL302 slides will cover Microsoft SQL
      Server.


Bookstore                SQL302 Module 2                   2
Warning!
• Below are some table name changes to be
  aware of in doing queries. We have created
  synonyms so either name should work.

            New Name              Old Name
            Orders                Order_filled
            Order_Lines           Orderlines


Bookstore                  SQL302 Module 2       3
SQL302 Contact Information



            P.O. Box 6142
            Laguna Niguel, CA 92607
            949-489-1472
            http://www.d2associates.com
            slides.1@dhdursoassociates.com
            Copyright 2001-2012All rights reserved.


Bookstore                            SQL302 Module 2   4
SQL302 Resources
• Bookstore database scripts found on
  box.net at
      http://tinyurl.com/SQLScripts
• Slides can be viewed on SlideShare…
      http://www.slideshare.net/OCDatabases
• Follow up questions?
      sql.support@dhdursoassociates.com

Bookstore              SQL302 Module 2        5
Relational Database with constraints (from text)




Bookstore                SQL302 Module 2                  6
Sample Employees Database




Bookstore2 &          SQL204 Module 1      7
Employees
More conventions
• Names can be surrounded with “ “ or [ ] as
  in [order details].
• Some of the PowerPoint slides may have
  this convention.
• Better practice is to use an underscore as in
  order_details.


Bookstore          SQL302 Module 2                8
SQL302

                   SQL Programming

            Part 1 – Joins: Natural, Self and Outer


Bookstore                  SQL302 Module 2            9
Joins
•   Inner (Covered in SQL202 course)
•   Natural Join
•   Self
•   Data Warehouse operators
•   Outer
      – Left
      – Right
      – Full
• Cross
• Theta
• We will cover some of the more advanced or subtle
  aspects of joins in this class
Bookstore               SQL302 Module 2               10
Natural Joins
• Table1 natural join table3 – automatically
  uses columns with same name
• Table 1 natural join table2 using(<column-
  list>
• Not yet available in SQL Server



Bookstore         SQL302 Module 2              11
Correlation Names (Table Aliases)

• Can abbreviate references to tables
• For example:
      Select e.name, j.payrange
      From employees as e
      Inner join job_information as j
      On e.jobcode = j.jobcode;



Bookstore               SQL302 Module 2   12
Self Joins
• Implements a recursive relationship
• Important in various applications
      –     Parts lists/assemblies
      –     HR
      –     Etc.
      –     Table joined to itself using correlation names



Bookstore                   SQL302 Module 2                  13
Self Joins

            SELECT e.*, m.name
            FROM employees AS e, employees
            AS m
            WHERE e.managerid =
            m.employeeid;




Bookstore               SQL302 Module 2      14
Bookstore   SQL302 Module 2   15
Datawarehouse clauses
• Two keywords that can be added to a
  grouped query
      – Rollup
      – Cube
• Places additional summary rows in the
  result set
• Result set is a true relational result set

Bookstore           SQL302 Module 2            16
Rollup
• Example: calculate average salaries by
  job_title_code and manager




Bookstore         SQL302 Module 2          17
Rollup results




Bookstore       SQL302 Module 2   18
cube
• Similar to rollup but computes summary
  rows in all dimensions




Bookstore        SQL302 Module 2           19
Cube results
• Add a new set of rows which total by year




Bookstore         SQL302 Module 2             20
Bookstore   SQL302 Module 2   21
Outer Joins
• Left – selects all rows from the left or first table,
  even if no match exists in the other table
      – Widely used in commercial practice
      – Especially useful for reporting
      – Can be slower and interfere with optimizer
• Right – same idea but all rows from right table
• Full – all rows form both tables


Bookstore                 SQL302 Module 2                 22
Left Outer Join

            Basic SQL 92 Syntax:
            Select <column-list>
            From <table1>
            Left join <table2>
            On <join condition>

Bookstore                SQL302 Module 2   23
Left Outer Join
• List all customers with their orders
• Include customers with no orders as well




Bookstore         SQL302 Module 2            24
Left-Join

            Basic Example:
            SELECT customer_first_name,
            customer_street, order_numb,
            order_date
            from customers as c
            left join orders as o
            on c.customer_numb =
            o.customer_numb

Bookstore               SQL302 Module 2    25
Left Join with Results




Bookstore           SQL302 Module 2   26
Negative Left Join
• List all the customers who have not placed
  any orders
• This is an example of a query which finds
  unmatched records




Bookstore         SQL302 Module 2              27
Negative Left-Join (Unmatched)
            Basic Example:
            SELECT customer_first_name,
            customer_last_name, order_numb,
            order_date
            from customers as c
            left join orders as o
            on c.customer_numb =
            o.customer_numb
            Where order_numb is null;
Bookstore               SQL302 Module 2       28
Bookstore   SQL302 Module 2   29
Left Join w/ Partial Match
• List all customers along with any orders
  placed in 1999
• If they did not place 1999 orders we still
  want to include them in the printout




Bookstore             SQL302 Module 2          30
Left Join w/ Partial Match
            Example:
            SELECT customer_first_name,
            customer_last_name, order_numb, order_date
            from customers as c
            Left join
            (select customer_numb, order_numb,
            order_date
                  From orders
                  Where year(order_date) = 1999) as d
            on c.customer_numb = d.customer_numb;


Bookstore                    SQL302 Module 2             31
Own Your Own
• List all books and their order totals for
  1999
• Show the book even if there were no
  orders placed in 1999




Bookstore          SQL302 Module 2            32
Theta Joins
• Theta joins involve inequalities in the
  matching conditions
• Can be used for some interesting queries
  which do not involve the usual primary
  key to foreign key matchings




Bookstore         SQL302 Module 2            33
Theta join
• Find all customers that live at the same address
      – Requires a self join of the customers table on address
        field




Bookstore                  SQL302 Module 2                       34
Theta join results




 • Can be further processed with a union query to
   consolidate names into a single list
Bookstore               SQL302 Module 2             35
SQL302

            SQL Programming

            Part 3– Set Operations


Bookstore         SQL302 Module 2    36
Set Operations
• More on unions
• Intersect
• Except




Bookstore          SQL302 Module 2   37
Unions
• Combines two or more tables
• Tables must be union compatible




Bookstore        SQL302 Module 2    38
Unions

      Select <column-list> from
      <table1>
      Union [ALL]
      Select <same-columns> from
      <table2>



Bookstore           SQL302 Module 2   39
Unions
• Example: consolidate two columns into one
  column




Bookstore          SQL302 Module 2            40
Union consolidation result
• Customers in same city




Bookstore             SQL302 Module 2    41
Unions
• Example: add a total row to a query result
• Code:
            use bookstore;
            select order_numb
                  , sum(quantity) as "Quantity"
                  , sum(cost_line)as "Total Cost"
            from orderlines
            group by order_numb
            union
            select NULL, sum(quantity),
            sum(cost_line)
            from orderlines;
Bookstore                 SQL302 Module 2           42
unions
• Example: add an element to a pick list




Bookstore         SQL302 Module 2          43
intersect
• The intersect operator finds rows in
  common between two tables
• Syntax
    Select <column-list> from <table1>
    intersect
    Select <same-columns> from <table2>



Bookstore         SQL302 Module 2         44
intersect
• Example: find cities in common between
  sources and customers
• Code
    select customer_city, customer_state,
    customer_zip
    from customers
    intersect
    select source_city, source_state,
    source_zip
    from sources; SQL302 Module 2
Bookstore                                   45
Except
• Finds all rows from first table that are not
  found in the second table
• Syntax:
    Select <column-list> from <table1>
    except
    Select <same-columns> from <table2>



Bookstore          SQL302 Module 2               46
except
• Example: find sources that are not located
  in any of our customer’s cities
• Code
    select source_city, source_state,
    source_zip
    from sources
    except
    select customer_city, customer_state,
    customer_zip
    from customers;SQL302 Module 2
Bookstore                                      47
SQL302

             SQL Programming

            Part 4 – Window Functions


Bookstore           SQL302 Module 2     48
Aggregate Functions
•   Count
•   Sum
•   Min
•   Max
•   Avg
•   Often used in conjunction with grouping
    and window functions
Bookstore          SQL302 Module 2            49
Window Functions
• Sort of like grouping, but aggregates can
  be taken along with straight columns in the
  select list
• The function is applied over a window
      – Partition by column
      – Partition by ()



Bookstore              SQL302 Module 2      50
Window Functions

      Basic syntax:

      Select …, window function(column)
             partition by <column>
      From <table>
      where <predicate>



Bookstore             SQL302 Module 2     51
Window Functions
     Example: Show salary along with average for the
     job_title and overall

     Code:
     use employeedb;
     select soc_sec_no,          name, salary
           , SUM(salary)         over(partition
     by job_title_code)          as [Job Code
     Average]
           , SUM(salary)         over() as
     [Average]
     from employees;
Bookstore                SQL302 Module 2               52
Exercise
• List all customers and their orders
      – Name nicely formatted
      – With orders in the year of 1999 (do not use
        between, etc.)
      – Show total order quantities and amounts
      – Only include orders with more than three
        order lines


Bookstore               SQL302 Module 2               53
Notes




Bookstore   SQL302 Module 2   54
Notes




Bookstore   SQL302 Module 2   55

Contenu connexe

En vedette

AIN102S Access string function sample queries
AIN102S Access string function sample queriesAIN102S Access string function sample queries
AIN102S Access string function sample queriesDan D'Urso
 
Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027Tim Rootsaert
 
Pharma Powerpoint 2
Pharma Powerpoint 2Pharma Powerpoint 2
Pharma Powerpoint 2guest4a9aba
 
GovProjects.org
GovProjects.orgGovProjects.org
GovProjects.orgF R
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualDan D'Urso
 
eParticipation in The Netherlands
eParticipation in The NetherlandseParticipation in The Netherlands
eParticipation in The NetherlandsBZK
 
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網RICK Lin
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1guest38bf
 
Managing Your Career In Tough Times 102308
Managing Your Career In Tough Times 102308Managing Your Career In Tough Times 102308
Managing Your Career In Tough Times 102308Joellyn Schwerdlin
 
KaDouce AutoBio
KaDouce AutoBioKaDouce AutoBio
KaDouce AutoBioKarine L
 
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...Andres Agostini, Future Knowledgist
 
Digital Public Records
Digital Public RecordsDigital Public Records
Digital Public RecordsRyan Thornburg
 
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...Andres Agostini, Future Knowledgist
 
我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況RICK Lin
 
Preparing Students
Preparing StudentsPreparing Students
Preparing StudentsKatie Turner
 
George Washington Teacher’s Institute
George Washington Teacher’s InstituteGeorge Washington Teacher’s Institute
George Washington Teacher’s Institutemoorebl
 
Show Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting DataShow Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting DataRyan Thornburg
 
My Print Portfolio
My Print PortfolioMy Print Portfolio
My Print Portfoliobeth7865
 

En vedette (20)

AIN102S Access string function sample queries
AIN102S Access string function sample queriesAIN102S Access string function sample queries
AIN102S Access string function sample queries
 
Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027
 
Pharma Powerpoint 2
Pharma Powerpoint 2Pharma Powerpoint 2
Pharma Powerpoint 2
 
GovProjects.org
GovProjects.orgGovProjects.org
GovProjects.org
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL Manual
 
eParticipation in The Netherlands
eParticipation in The NetherlandseParticipation in The Netherlands
eParticipation in The Netherlands
 
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
資訊服務業技術趨勢-創業懶人包-青年創業及圓夢網
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
 
Managing Your Career In Tough Times 102308
Managing Your Career In Tough Times 102308Managing Your Career In Tough Times 102308
Managing Your Career In Tough Times 102308
 
KaDouce AutoBio
KaDouce AutoBioKaDouce AutoBio
KaDouce AutoBio
 
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
ArchEvolution In 1 Slide! By Copyright 2009 Andres Agostini (Andy) - Arlingto...
 
Digital Public Records
Digital Public RecordsDigital Public Records
Digital Public Records
 
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
 
我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況
 
PREMIS FOTOGRAFIA FILOSOFICA
PREMIS FOTOGRAFIA FILOSOFICAPREMIS FOTOGRAFIA FILOSOFICA
PREMIS FOTOGRAFIA FILOSOFICA
 
Preparing Students
Preparing StudentsPreparing Students
Preparing Students
 
George Washington Teacher’s Institute
George Washington Teacher’s InstituteGeorge Washington Teacher’s Institute
George Washington Teacher’s Institute
 
Show Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting DataShow Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting Data
 
My Print Portfolio
My Print PortfolioMy Print Portfolio
My Print Portfolio
 
Test 1
Test 1Test 1
Test 1
 

Similaire à SQL302 Intermediate SQL Workshop 2

SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2Dan D'Urso
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2Dan D'Urso
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3Dan D'Urso
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1Dan D'Urso
 
SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualDan D'Urso
 
SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3Dan D'Urso
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignDan D'Urso
 
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfRivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfFrederic Descamps
 
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgradeDevelopers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrademCloud
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3Dan D'Urso
 
LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartDan D'Urso
 
Introduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache CassandraIntroduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache CassandraLuke Tillman
 
Implementing Tables and Views.pptx
Implementing Tables and Views.pptxImplementing Tables and Views.pptx
Implementing Tables and Views.pptxLuisManuelUrbinaAmad
 
Developer's Approach to Code Management
Developer's Approach to Code ManagementDeveloper's Approach to Code Management
Developer's Approach to Code ManagementMichael Rosenblum
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1MariaDB plc
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)Michael Rys
 
Distributed database
Distributed databaseDistributed database
Distributed databaseNasIr Irshad
 
Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Zohar Elkayam
 
20180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk220180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk2Kunihisa Abukawa
 

Similaire à SQL302 Intermediate SQL Workshop 2 (20)

SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
 
SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL Manual
 
sql_bootcamp.pdf
sql_bootcamp.pdfsql_bootcamp.pdf
sql_bootcamp.pdf
 
SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL Design
 
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdfRivieraJUG - MySQL 8.0 - What's new for developers.pdf
RivieraJUG - MySQL 8.0 - What's new for developers.pdf
 
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgradeDevelopers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
 
LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with Lucidchart
 
Introduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache CassandraIntroduction to Data Modeling with Apache Cassandra
Introduction to Data Modeling with Apache Cassandra
 
Implementing Tables and Views.pptx
Implementing Tables and Views.pptxImplementing Tables and Views.pptx
Implementing Tables and Views.pptx
 
Developer's Approach to Code Management
Developer's Approach to Code ManagementDeveloper's Approach to Code Management
Developer's Approach to Code Management
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)
 
Distributed database
Distributed databaseDistributed database
Distributed database
 
Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)Oracle Database Advanced Querying (2016)
Oracle Database Advanced Querying (2016)
 
20180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk220180929 jssug 10_a5_sql_mk2
20180929 jssug 10_a5_sql_mk2
 

Plus de Dan D'Urso

Database Normalization
Database NormalizationDatabase Normalization
Database NormalizationDan D'Urso
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingDan D'Urso
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedDan D'Urso
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingDan D'Urso
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using PythonDan D'Urso
 
Stem conference
Stem conferenceStem conference
Stem conferenceDan D'Urso
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joinsDan D'Urso
 
AIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisAIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisDan D'Urso
 
Course Catalog
Course CatalogCourse Catalog
Course CatalogDan D'Urso
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualDan D'Urso
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL MedianDan D'Urso
 
AIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesAIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesDan D'Urso
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesDan D'Urso
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1Dan D'Urso
 
AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2Dan D'Urso
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosDan D'Urso
 
Course Catalog
Course CatalogCourse Catalog
Course CatalogDan D'Urso
 

Plus de Dan D'Urso (18)

Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database Diagramming
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 Accelerated
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic Training
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using Python
 
Stem conference
Stem conferenceStem conference
Stem conference
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joins
 
AIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisAIN106 Access Reporting and Analysis
AIN106 Access Reporting and Analysis
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL Manual
 
AIN100
AIN100AIN100
AIN100
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL Median
 
AIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesAIN102 Microsoft Access Queries
AIN102 Microsoft Access Queries
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access Queries
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1
 
AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access Macros
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 

Dernier

Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 

Dernier (20)

Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 

SQL302 Intermediate SQL Workshop 2

  • 1. SQL302 Intermediate SQL Programming Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T- SQL Fundamentals by Itzki Ben-gan Workshop 2 – Joins, Set Operations, Window Functions Bookstore SQL302 Module 2 1
  • 2. Note on SQL302 Slides • These slides were originally designed to support a single SQL course which was used for any of MS Access, MySQL, Oracle and SQL Server. • As such you may see here slides developed in any one of the above products. • We are in the process of migrating the Oracle, Access, and MySQL slides out into their own slide sets. The SQL302 slides will cover Microsoft SQL Server. Bookstore SQL302 Module 2 2
  • 3. Warning! • Below are some table name changes to be aware of in doing queries. We have created synonyms so either name should work. New Name Old Name Orders Order_filled Order_Lines Orderlines Bookstore SQL302 Module 2 3
  • 4. SQL302 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2012All rights reserved. Bookstore SQL302 Module 2 4
  • 5. SQL302 Resources • Bookstore database scripts found on box.net at http://tinyurl.com/SQLScripts • Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases • Follow up questions? sql.support@dhdursoassociates.com Bookstore SQL302 Module 2 5
  • 6. Relational Database with constraints (from text) Bookstore SQL302 Module 2 6
  • 7. Sample Employees Database Bookstore2 & SQL204 Module 1 7 Employees
  • 8. More conventions • Names can be surrounded with “ “ or [ ] as in [order details]. • Some of the PowerPoint slides may have this convention. • Better practice is to use an underscore as in order_details. Bookstore SQL302 Module 2 8
  • 9. SQL302 SQL Programming Part 1 – Joins: Natural, Self and Outer Bookstore SQL302 Module 2 9
  • 10. Joins • Inner (Covered in SQL202 course) • Natural Join • Self • Data Warehouse operators • Outer – Left – Right – Full • Cross • Theta • We will cover some of the more advanced or subtle aspects of joins in this class Bookstore SQL302 Module 2 10
  • 11. Natural Joins • Table1 natural join table3 – automatically uses columns with same name • Table 1 natural join table2 using(<column- list> • Not yet available in SQL Server Bookstore SQL302 Module 2 11
  • 12. Correlation Names (Table Aliases) • Can abbreviate references to tables • For example: Select e.name, j.payrange From employees as e Inner join job_information as j On e.jobcode = j.jobcode; Bookstore SQL302 Module 2 12
  • 13. Self Joins • Implements a recursive relationship • Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation names Bookstore SQL302 Module 2 13
  • 14. Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid; Bookstore SQL302 Module 2 14
  • 15. Bookstore SQL302 Module 2 15
  • 16. Datawarehouse clauses • Two keywords that can be added to a grouped query – Rollup – Cube • Places additional summary rows in the result set • Result set is a true relational result set Bookstore SQL302 Module 2 16
  • 17. Rollup • Example: calculate average salaries by job_title_code and manager Bookstore SQL302 Module 2 17
  • 18. Rollup results Bookstore SQL302 Module 2 18
  • 19. cube • Similar to rollup but computes summary rows in all dimensions Bookstore SQL302 Module 2 19
  • 20. Cube results • Add a new set of rows which total by year Bookstore SQL302 Module 2 20
  • 21. Bookstore SQL302 Module 2 21
  • 22. Outer Joins • Left – selects all rows from the left or first table, even if no match exists in the other table – Widely used in commercial practice – Especially useful for reporting – Can be slower and interfere with optimizer • Right – same idea but all rows from right table • Full – all rows form both tables Bookstore SQL302 Module 2 22
  • 23. Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition> Bookstore SQL302 Module 2 23
  • 24. Left Outer Join • List all customers with their orders • Include customers with no orders as well Bookstore SQL302 Module 2 24
  • 25. Left-Join Basic Example: SELECT customer_first_name, customer_street, order_numb, order_date from customers as c left join orders as o on c.customer_numb = o.customer_numb Bookstore SQL302 Module 2 25
  • 26. Left Join with Results Bookstore SQL302 Module 2 26
  • 27. Negative Left Join • List all the customers who have not placed any orders • This is an example of a query which finds unmatched records Bookstore SQL302 Module 2 27
  • 28. Negative Left-Join (Unmatched) Basic Example: SELECT customer_first_name, customer_last_name, order_numb, order_date from customers as c left join orders as o on c.customer_numb = o.customer_numb Where order_numb is null; Bookstore SQL302 Module 2 28
  • 29. Bookstore SQL302 Module 2 29
  • 30. Left Join w/ Partial Match • List all customers along with any orders placed in 1999 • If they did not place 1999 orders we still want to include them in the printout Bookstore SQL302 Module 2 30
  • 31. Left Join w/ Partial Match Example: SELECT customer_first_name, customer_last_name, order_numb, order_date from customers as c Left join (select customer_numb, order_numb, order_date From orders Where year(order_date) = 1999) as d on c.customer_numb = d.customer_numb; Bookstore SQL302 Module 2 31
  • 32. Own Your Own • List all books and their order totals for 1999 • Show the book even if there were no orders placed in 1999 Bookstore SQL302 Module 2 32
  • 33. Theta Joins • Theta joins involve inequalities in the matching conditions • Can be used for some interesting queries which do not involve the usual primary key to foreign key matchings Bookstore SQL302 Module 2 33
  • 34. Theta join • Find all customers that live at the same address – Requires a self join of the customers table on address field Bookstore SQL302 Module 2 34
  • 35. Theta join results • Can be further processed with a union query to consolidate names into a single list Bookstore SQL302 Module 2 35
  • 36. SQL302 SQL Programming Part 3– Set Operations Bookstore SQL302 Module 2 36
  • 37. Set Operations • More on unions • Intersect • Except Bookstore SQL302 Module 2 37
  • 38. Unions • Combines two or more tables • Tables must be union compatible Bookstore SQL302 Module 2 38
  • 39. Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2> Bookstore SQL302 Module 2 39
  • 40. Unions • Example: consolidate two columns into one column Bookstore SQL302 Module 2 40
  • 41. Union consolidation result • Customers in same city Bookstore SQL302 Module 2 41
  • 42. Unions • Example: add a total row to a query result • Code: use bookstore; select order_numb , sum(quantity) as "Quantity" , sum(cost_line)as "Total Cost" from orderlines group by order_numb union select NULL, sum(quantity), sum(cost_line) from orderlines; Bookstore SQL302 Module 2 42
  • 43. unions • Example: add an element to a pick list Bookstore SQL302 Module 2 43
  • 44. intersect • The intersect operator finds rows in common between two tables • Syntax Select <column-list> from <table1> intersect Select <same-columns> from <table2> Bookstore SQL302 Module 2 44
  • 45. intersect • Example: find cities in common between sources and customers • Code select customer_city, customer_state, customer_zip from customers intersect select source_city, source_state, source_zip from sources; SQL302 Module 2 Bookstore 45
  • 46. Except • Finds all rows from first table that are not found in the second table • Syntax: Select <column-list> from <table1> except Select <same-columns> from <table2> Bookstore SQL302 Module 2 46
  • 47. except • Example: find sources that are not located in any of our customer’s cities • Code select source_city, source_state, source_zip from sources except select customer_city, customer_state, customer_zip from customers;SQL302 Module 2 Bookstore 47
  • 48. SQL302 SQL Programming Part 4 – Window Functions Bookstore SQL302 Module 2 48
  • 49. Aggregate Functions • Count • Sum • Min • Max • Avg • Often used in conjunction with grouping and window functions Bookstore SQL302 Module 2 49
  • 50. Window Functions • Sort of like grouping, but aggregates can be taken along with straight columns in the select list • The function is applied over a window – Partition by column – Partition by () Bookstore SQL302 Module 2 50
  • 51. Window Functions Basic syntax: Select …, window function(column) partition by <column> From <table> where <predicate> Bookstore SQL302 Module 2 51
  • 52. Window Functions Example: Show salary along with average for the job_title and overall Code: use employeedb; select soc_sec_no, name, salary , SUM(salary) over(partition by job_title_code) as [Job Code Average] , SUM(salary) over() as [Average] from employees; Bookstore SQL302 Module 2 52
  • 53. Exercise • List all customers and their orders – Name nicely formatted – With orders in the year of 1999 (do not use between, etc.) – Show total order quantities and amounts – Only include orders with more than three order lines Bookstore SQL302 Module 2 53
  • 54. Notes Bookstore SQL302 Module 2 54
  • 55. Notes Bookstore SQL302 Module 2 55