CS122 Using Relational Databases and SQL

Slides:



Advertisements
Similar presentations
Aggregate Functions Presenter: Sushma Bandekar CS 157(A) – Fall 2006.
Advertisements

4 Copyright © 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Chapter 6 Set Functions.
5 Copyright © 2007, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
4 การใช้ SQL Functions. Copyright © 2007, Oracle. All rights reserved What Are Group Functions? Group functions operate on sets of rows to give.
Chapter 11 Group Functions
LECTURE 10.  Group functions operate on sets of rows to give one result per group.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Aggregates.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 6: Set Functions.
Introduction to Oracle9i: SQL1 SQL Group Functions.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Aggregates.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 5: Subqueries and Set Operations.
Structured Query Language Part I Chapter Three CIS 218.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 8: Subqueries.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 6 Group Functions. Chapter Objectives  Differentiate between single-row and multiple-row functions  Use the SUM and AVG functions for numeric.
Chapter 3 Single-Table Queries
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
4 Copyright © 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group Functions.
Using Special Operators (LIKE and IN)
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Agenda for Class - 03/04/2014 Answer questions about HW#5 and HW#6 Review query syntax. Discuss group functions and summary output with the GROUP BY statement.
April 2002 Information Systems Design John Ogden & John Wordsworth 1 Database Design SQL (1) John Wordsworth Department of Computer Science The University.
Lesson 4: Querying a Database. 2 Learning Objectives After studying this lesson, you will be able to:  Create, save, and run select queries  Set query.
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
SQL LANGUAGE TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 2. Single Table Queries.
Lecture 7: Subqueries Tarik Booker California State University, Los Angeles.
Tarik Booker CS 122. What we will cover… Tables (review) SELECT statement DISTINCT, Calculated Columns FROM Single tables (for now…) WHERE Date clauses,
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 4. Subqueries and joins.
CS122 Using Relational Databases and SQL
In this session, you will learn to:
SQL AGGREGATE FUNCTIONS
Tarik Booker California State University, Los Angeles October 21, 2014
Chapter 3 Introduction to SQL(3)
Using Relational Databases and SQL
The Database Exercises Fall, 2009.
Group Functions Lab 6.
CS122 Using Relational Databases and SQL
Working with Tables: Join, Functions and Grouping
CS122 Using Relational Databases and SQL
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Aggregating Data Using Group Functions
SQL – Entire Select.
Chapter 4 Summary Query.
CS122 Using Relational Databases and SQL
CS122 Using Relational Databases and SQL
Reporting Aggregated Data Using the Group Functions
Query Functions.
CS1222 Using Relational Databases and SQL
Section 4 - Sorting/Functions
CS122 Using Relational Databases and SQL
Reporting Aggregated Data Using the Group Functions
Reporting Aggregated Data Using the Group Functions
CS1222 Using Relational Databases and SQL
Shelly Cashman: Microsoft Access 2016
CS1222 Using Relational Databases and SQL
CS122 Using Relational Databases and SQL
Group Operations Part IV.
Presentation transcript:

CS122 Using Relational Databases and SQL 2/23/2019 CS122 Using Relational Databases and SQL 3. Aggregate calculations Daniel Firpo Slides prepared by Randy Moss Department of Computer Science California State University, Los Angeles

Outline Aggregate calculations for a table 2/23/2019 Outline Aggregate calculations for a table Aggregate calculations for groups Function followed by field or expression in parentheses Can use AS and an alias column name Can use Aggregate as part of expression 3. Aggregate Calculations CS1222_W2018

What is an Aggregate? Summarizes values from entire groups of rows 2/23/2019 What is an Aggregate? Summarizes values from entire groups of rows SUM: To calculate totals AVG: To calculate averages COUNT: To count the number of records MIN: To report the minimum value MAX: To report the maximum value 3. Aggregate Calculations CS1222_W2018

Sum Add up a column Only for numeric attributes 2/23/2019 Sum Add up a column Only for numeric attributes Any null values will be ignored. E.X. Report the total time in seconds of all tracks SELECT Sum (lengthseconds) FROM Tracks 3. Aggregate Calculations CS1222_W2018

2/23/2019 Avg AVG ignores nulls Report the average length in minutes of all tracks SELECT Avg(lengthseconds)/60 FROM Tracks 3. Aggregate Calculations CS1222_W2018

Avg 30! SELECT Avg(age) FROM Employees The result is 20 or 30? 01 25 2/23/2019 Avg Employees eid age 01 25 02 NULL 03 35 SELECT Avg(age) FROM Employees The result is 20 or 30? 30! 3. Aggregate Calculations CS1222_W2018

Count Take as an argument either a field name or an asterisk(*) 2/23/2019 Count Take as an argument either a field name or an asterisk(*) E.X. Report the number of members in the members table SELECT Count(*) AS NumMembers FROM Members 3. Aggregate Calculations CS1222_W2018

Count Difference between Count(*) and Count (field) SELECT Count(age) 2/23/2019 Count Difference between Count(*) and Count (field) SELECT Count(age) FROM Employees Employees 2! eid age 01 25 02 NULL 03 35 SELECT Count(*) FROM Employees 3! 3. Aggregate Calculations CS1222_W2018

Min, Max Report the minimum and maximum values. 2/23/2019 Min, Max Report the minimum and maximum values. Can be used with numeric datatypes, dates and text E.X. Report the shortest and the longest track lengths in seconds SELECT Min(lengthseconds) as Shortest, Max(lengthseconds) as Longest FROM Tracks 3. Aggregate Calculations CS1222_W2018

Aggregate functions summary 2/23/2019 Aggregate functions summary Can be used as part of an expression Use WHERE to limit the number of rows being aggregated Multiple aggregate functions can be used together Use AS to give an aggregate function an alias 3. Aggregate Calculations CS1222_W2018

Discussions SELECT avg(lengthseconds) FROM Tracks 2/23/2019 Discussions SELECT avg(lengthseconds) FROM Tracks Returns a SINGLE VALUE! SELECT lengthseconds Returns a TABLE! 3. Aggregate Calculations CS1222_W2018

Discussions SELECT tracktitle, avg(lengthseconds) FROM Tracks 2/23/2019 Discussions SELECT tracktitle, avg(lengthseconds) FROM Tracks Does this query make any sense? No, we need group by! 3. Aggregate Calculations CS1222_W2018

Outline Aggregate calculations for a table 2/23/2019 Outline Aggregate calculations for a table Aggregate calculations for groups 3. Aggregate Calculations CS1222_W2018

2/23/2019 What are groups? Member id Gender Region Country 11 M TX USA 12 ON CANADA 13 14 F VA 15 16 A group contains a collection of rows that have the same attribute(s) values. 3. Aggregate Calculations CS1222_W2018

What are groups? (cont.) Example groups All male members 2/23/2019 What are groups? (cont.) Example groups All male members Members from USA Members from Virginia female members from Ontario 3. Aggregate Calculations CS1222_W2018

2/23/2019 GROUP BY If SELECT has only aggregates, will report just one row for the entire set of records If non-aggregate fields are included in SELECT clause, query will report one row for each combination of non-aggregate field values with aggregates calculated for each Must include a GROUP BY clause listing the non-aggregate fields The more fields in the GROUP BY clause, the more rows will be reported Proper order of clauses: SELECT column, Aggregate(column) As column_name FROM tablename WHERE condition GROUP BY column ORDER BY column 3. Aggregate Calculations CS1222_W2018

Aggregate a single group 2/23/2019 Aggregate a single group Format: Select count|max|min|avg|sum From table_name Where conditions The conditions to form a group 3. Aggregate Calculations CS1222_W2018

Aggregate a single group example1: 2/23/2019 Aggregate a single group example1: Report the number of male members Select count(*) From Members Where gender = ‘m’ 3. Aggregate Calculations CS1222_W2018

Aggregate a single group example: 2/23/2019 Aggregate a single group example: Report the number of female members from Ontario Select count(*) From Members Where gender = ‘f’ and region = ‘on’ 3. Aggregate Calculations CS1222_W2018

Aggregate multiple groups 2/23/2019 Aggregate multiple groups How to answer the following queries using a single query? Report the number of male AND female members? For each distinct combination of gender and region, report the number of members Use group by!! 3. Aggregate Calculations CS1222_W2018

2/23/2019 GROUP BY When you include non-aggregate fields with aggregates, you must include a GROUP BY clause listing the non-aggregate fields. One row will be reported for each combination of the non-aggregate fields. SELECT column, Aggregate (column) FROM Tablename WHERE condition GROUP BY column ORDER BY column 3. Aggregate Calculations CS1222_W2018

What is a group? Report the number of male AND female members? 2/23/2019 What is a group? Report the number of male AND female members? SELECT gender, count(*) FROM Members GROUP BY gender Member id Gender Region Country 11 M TX USA 12 ON CANADA 13 14 F VA 15 16 Gender Count M 4 F 2 3. Aggregate Calculations CS1222_W2018

GROUP BY Example 2/23/2019 Select Count(*) As Num From Members Where Email Is Not Null Num ----------- 12 Select Gender, Count(*) As Num From Members Where Email Is Not Null Group By Gender Gender Num ------ ----------- F 2 M 10 3. Aggregate Calculations CS1222_W2018

2/23/2019 What is a group? For each distinct combination of gender and region, report the number of members SELECT gender, region, count(*) FROM Members GROUP BY gender, region Member id Gender Region Country 11 M TX USA 12 ON CANADA 13 14 F VA 15 16 Gender region Count M TX 2 M ON 1 M VA 1 F VA 1 F ON 1 3. Aggregate Calculations CS1222_W2018

GROUP BY Example (cont) 2/23/2019 Select Region, Gender, Count(*) As Num From Members Where Email Is Not Null Group By Region, Gender Region Gender Num ------- ------ ---- IN F 1 VT F 1 CA M 1 GA M 1 IN M 1 NC M 1 NY M 1 OH M 1 ONT M 1 TX M 2 VA M 1 3. Aggregate Calculations CS1222_W2018

GROUP BY Example Report the total time for EACH TITLE ID 2/23/2019 GROUP BY Example Report the total time for EACH TITLE ID SELECT titleId, sum(lengthseconds) FROM Tracks GROUP BY titleId 3. Aggregate Calculations CS1222_W2018

GROUP BY Example (cont.) 2/23/2019 GROUP BY Example (cont.) Report the shortest and longest track lengths for EACH TITLE ID SELECT titleId, Min(lengthseconds), Max(lengthseconds) FROM Tracks GROUP BY titleId 3. Aggregate Calculations CS1222_W2018

GROUP BY Example (cont) 2/23/2019 GROUP BY Example (cont) Report the number of members for each combination of country and gender SELECT country, gender, count(*) FROM Members GROUP BY country, gender 3. Aggregate Calculations CS1222_W2018

2/23/2019 GROUP BY summary Aggregate on distinct value(s) of the group-by attribute(s) Group-by attribute(s) must be the same as the non-aggregate attributes in the SELECT clause The more fields in the GROUP BY clause, the more rows will be reported 3. Aggregate Calculations CS1222_W2018

2/23/2019 HAVING HAVING restricts results based on aggregated values (eliminate groups) HAVING always uses an aggregate function as its test Proper order of clauses: SELECT column, Aggregate(column) FROM tablename WHERE condition GROUP BY column HAVING condition ORDER BY column 3. Aggregate Calculations CS1222_W2018

2/23/2019 HAVING vs. WHERE WHERE restricts results prior to aggregate calculations based on individual row values HAVING restricts results based on aggregated values HAVING always uses an aggregate function as its test Proper order of clauses: SELECT column, Aggregate(column) As column_name FROM tablename WHERE condition GROUP BY column HAVING condition ORDER BY column 3. Aggregate Calculations CS1222_W2018

Base selection with aggregate 2/23/2019 HAVING Example For each titleID, report the average length of all tracks. Select TitleID, Avg(lengthseconds) As AvgLength From Tracks Group by TitleID   TitleID AvgLength ----------- ----------- 1 279 3 212 4 221 5 231 6 532 7 309 Base selection with aggregate 3. Aggregate Calculations CS1222_W2018

2/23/2019 HAVING Example (cont) Select TitleID, Avg(lengthseconds) As AvgLength From Tracks Group by TitleID Having Avg(lengthseconds)>240   TitleID AvgLength ----------- ----------- 1 279 6 532 7 309 HAVING eliminates aggregated averages of 240 seconds or less, so calculations match original but with fewer resulting rows 3. Aggregate Calculations CS1222_W2018

2/23/2019 HAVING Example (cont) Select TitleID, Avg(lengthseconds) As AvgLength From Tracks Where lengthseconds>240 Group by TitleID   TitleID AvgLength ----------- ----------- 1 327 3 294 4 352 5 282 6 532 7 325 WHERE eliminates detail records with length of 240 seconds or less, so reported averages are higher and no groups are eliminated. 3. Aggregate Calculations CS1222_W2018

2/23/2019 HAVING Example (cont) Select TitleID, Avg(lengthseconds) As AvgLength From Tracks Where lengthseconds>400 Group by TitleID   TitleID AvgLength ----------- ----------- 1 402.0000 6 565.7500 7 441.0000 WHERE eliminates detail records with length of 400 seconds or less, so reported averages are higher. 3. Aggregate Calculations CS1222_W2018

Summary Aggregate calculations for a table 2/23/2019 Summary Aggregate calculations for a table Sum, max, min, avg, count Aggregate calculations for groups Group by having 3. Aggregate Calculations CS1222_W2018