ZEIT2301 Design of Information Systems SQL: Computing Statistics School of Engineering and Information Technology Dr Kathryn Merrick.

Slides:



Advertisements
Similar presentations
SQL Structured Query Language. SQL The SELECT Statement The SELECT statement is used to select data from a table. The tabular result is stored in a result.
Advertisements

4 Copyright © 2004, Oracle. All rights reserved. Reporting Aggregated Data Using the Group 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.
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 6: Set Functions.
1ISM - © 2010 Houman Younessi Lecture 3 Convener: Houman Younessi Information Systems Spring 2011.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
ZEIT2301- Database Design Normalisation School of Engineering and Information Technology Dr Kathryn Merrick Bldg 16, Rm 212 (Thursdays and Fridays.
Computer Science 101 Web Access to Databases SQL – Extended Form.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
LOGO 1 Lab_02: Basic SQL. 2 Outline  Database Tables  SQL Statements  Semicolon after SQL Statements?  SQL DML and DDL  SQL SELECT Statement  SQL.
Chapter 3 Single-Table Queries
Structured Query Language. SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems.
ZEIT2301 Design of Information Systems SQL: Creating a Database School of Engineering and Information Technology Dr Kathryn Merrick.
Functions Oracle Labs 5 & 6. 2/3/2005Adapted from Introduction to Oracle: SQL and PL/SQL 2 SQL Functions Function arg n arg 2 arg 1. Input Resulting Value.
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.
Lecture7:Data Manipulation in SQL Advanced Queries Prepared by L. Nouf Almujally Ref. Chapter5 Lecture7 1.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
LOGO 1 Lab_04: Basic SQL. 2 Outline  The ORDER BY Keyword  SQL ORDER BY Syntax  SQL NULL Values.
SQL. คำสั่ง SQL SQL stands for Structured Query Language is a standard language for accessing and manipulating databases.
Lab_03: Basic SQL.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
SQL Aggregation Oracle and ANSI Standard SQL Lecture 9.
Introduction to Functions – Single Row Functions.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IS6146 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures Rob Gleasure robgleasure.com.
1 БАЗЫ ДАННЫХ. 2 ПРЕДЛОЖЕНИЯ SQL ВЫБОРКА - SELECT SELECT [предикат] { * | таблица.* | [таблица.]поле_1 [AS псевдоним_1] [, [таблица.]поле_2 [AS псевдоним_2]
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
1 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
1 Copyright © 2009, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
SQL Structured Query Language. SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
Rob Gleasure robgleasure.com
In this session, you will learn to:
Writing Basic SQL SELECT Statements
Aggregating Data Using Group Functions
Chapter 3 Introduction to SQL(3)
CS 405G: Introduction to Database Systems
Rob Gleasure robgleasure.com
SQL – Entire Select.
Aggregations Various Aggregation Functions GROUP BY HAVING.
Chapter 4 Summary Query.
Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Lesson Plan Instructional Objective Learning Objective
Reporting Aggregated Data Using the Group Functions
Section 4 - Sorting/Functions
Reporting Aggregated Data Using the Group Functions
Reporting Aggregated Data Using the Group Functions
More SQL Statements.
分组函数 Schedule: Timing Topic 35 minutes Lecture 40 minutes Practice
Concept of grouping SELECT statement have:
Aggregating Data Using Group Functions
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

ZEIT2301 Design of Information Systems SQL: Computing Statistics School of Engineering and Information Technology Dr Kathryn Merrick

Topic 11: SQL Computing Statistics In this lecture you will learn to use functions in SQL to compute simple statistics on data 1. Aggregating functions 2. Ordering functions 3. String functions 4. Date functions Reference:

1. Aggregate Functions Functions that operate on a single column (or expression) and return a single value COUNT – counts the number of values SUM – returns the total of the values AVG – returns the average of the values MIN – returns the minimum value MAX – returns the maximum value Used in SELECT clause NOT allowed in WHERE clause (very common mistake)

COUNT() How many clubs are there? SELECT COUNT(*) FROM sportClub; How many club presidents are there? SELECT COUNT(president) FROM sportClub; sportClub (sport, contactNo, sponsor, president, annualBudget ) Query returns a table with one row with one column. * is a special shorthand; Query counts all rows of the table Does not count nulls in the “president” column

COUNT(DISTINCT) How many different club sponsors are there? SELECT COUNT (DISTINCT sponsor) FROM sportClub; (supported by Oracle and SQL Server but not by Access) sportClub (sport, contactNo, sponsor, president, annualBudget ) Discards duplicates

SUM() Each club has an annual budget. What is the total budget amount for all clubs? SELECT SUM(annualBudget) FROM sportClub; sportClub (sport, contactNo, sponsor, president, annualBudget ) Query returns a table with one row with one column. Hint: The NRL Salary Cap for 2011 is $4.3m for the 25 highest paid players at each club.

AVG(), MIN(), MAX() Find the average, minimum and maximum cost of the clubs’ budgets SELECT AVG(annualBudget), MIN(annualBudget), MAX(annualBudget) FROM sportClub; Query returns one row with three columns.

Review: Column Name Aliases Columns can be renamed in the result table using the AS clause to give more meaningful output Also useful to avoid display of system generated column names for calculated columns (MsAccess uses “Expr1”) Select SUM(annualBudget) AS TotalBudget

The Bike Database Revisited Bike name* Number of riders* Centre of mass height Harley Harley Honda Honda Road conditions* Coefficient of friction Icy0.1 Wet0.5 Dry0.9 Scenario ID* Bike name Number of riders Road conditions Can stoppie 1Harley1Dryfalse 2Harley2Dryfalse 3Honda1Drytrue 4Honda2Drytrue Bike name* Wheelbase Harley1.588 Honda1.458

Aliasing Examples SELECT MIN(wheelbase) AS minWheelbase FROM Bikes; SELECT MAX(scenarioID) AS maxScenarioID FROM Scenarios; SELECT AVG(wheelbase) AS avgWheelbase FROM Bikes; SELECT COUNT(wheelbase) AS smallWheelbases FROM Bikes WHERE wheelbase < 1.5;

Aggregating Results The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. Eg: to find the total value of all orders by each customer, we can use the GROUP BY statement to group customers. SELECT customer, SUM(orderPrice) FROM Orders GROUP BY customer Orders(orderID, orderDate, orderPrice, customer)

Aggregating Results Solution orderIDorderDateorderPricecustomer 12008/11/121000Hansen 22008/10/231600Nilsen 32008/09/02700Hansen 42008/09/03300Hansen 52008/08/302000Jensen 62008/10/04100Nilsen customerSUM(orderPrice) Hansen2000 Nilsen1700 Jensen2000 Orders Query result

Filtering Groups Individual rows can be filtered using a WHERE clause BUT groups must be filtered using a HAVING clause Eg: suppose we only want to display customer order totals less than $2000: SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING SUM(OrderPrice) < 2000 customerSUM(OrderPrice) Nilsen1700

In Class Exercise What is the result of the following query on the Orders table? SELECT customer, SUM(orderPrice) FROM Orders WHERE customer='Hansen' OR customer='Jensen' GROUP BY customer HAVING SUM(orderPrice) > 1500 orderIDorderDateorderPricecustomer 12008/11/121000Hansen 22008/10/231600Nilsen 32008/09/02700Hansen 42008/09/03300Hansen 52008/08/302000Jensen 62008/10/04100Nilsen

2. Order Functions Find the first value of the orderPrice column SELECT FIRST(orderPrice) FROM Orders Equivalent to: SELECT orderPrice FROM Orders ORDER BY orderID LIMIT 1 Find the last value of the orderPrice column: SELECT LAST(orderPrice) FROM Orders Equivalent to: SELECT prderPrice FROM Orders ORDER BY orderID DESC LIMIT 1

3. String Functions Functions that operate on strings (varchars) UCASE() – convert a string to uppercase LCASE() – convert a string to lower case MID() – extract characters from the middle of a string LEN() – find the length of a string

UCASE() personIDlastNamefirstNameaddresscity 1HansenOlaTimoteivn 10Sandnes 2SvendsonToveBorgvn 23Sandnes 3PettersenKariStorgt 20Stavanger SELECT UCASE(lastName) as lastName, firstName FROM Persons lastNamefirstName HANSENOla SVENDSONTove PETTERSENKari Persons

MID() SELECT MID(city,1,4) as SmallCity FROM Persons Column name Start Character End Character SmallCity Sand Stav

LEN() SELECT LEN(Address) as LengthOfAddress FROM Persons LengthOfAddress

4. Date Functions Functions for manipulating dates NOW() – get the current system date and time SELECT productName, unitPrice, NOW() as perDate FROM Products prod_IdproductNameunitunitPrice 1Jarlsberg1000 g Mascarpone1000 g Gorgonzola1000 g15.67 productNameunitPriceperDate Jarlsberg /7/ :25:02 AM Mascarpone /7/ :25:02 AM Gorgonzola /7/ :25:02 AM

Summary After today’s lecture you should be able to write or interpret queries that include: Aggregating functions Ordering functions String functions Date functions