GIFT Department of Computing Science. CS-217: Database Systems. Lab-4 Manual. Reporting Aggregated Data using Group Functions

Similar documents
What Are Group Functions? Reporting Aggregated Data Using the Group Functions. Objectives. Types of Group Functions

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113)

CS2 Current Technologies Lecture 2: SQL Programming Basics

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Intermediate SQL: Aggregated Data, Joins and Set Operators

Reporting Aggregated Data Using the Group Functions. Copyright 2004, Oracle. All rights reserved.

Database implementation Further SQL

SQL Functions (Single-Row, Aggregate)

KORA. RDBMS Concepts II

Objectives. After completing this lesson, you should be able to do the following:

SQL. Char (30) can store ram, ramji007 or 80- b

Chapter 16: Advanced MySQL- Grouping Records and Joining Tables. Informatics Practices Class XII. By- Rajesh Kumar Mishra

Databases - 5. Problems with the relational model Functions and sub-queries

SQL Structured Query Language Introduction

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

GIFT Department of Computing Science. [Spring 2016] CS-217: Database Systems. Lab-3 Manual. Single Row Functions in SQL

Visit for more.

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

1 SQL Structured Query Language

1 SQL Structured Query Language

Slicing and Dicing Data in CF and SQL: Part 1

1Z0-071 Exam Questions Demo Oracle. Exam Questions 1Z Oracle Database 12c SQL.

SQL Data Manipulation Language. Lecture 5. Introduction to SQL language. Last updated: December 10, 2014

1Z0-071 Exam Questions Demo Oracle. Exam Questions 1Z Oracle Database 12c SQL.

Database 2: Slicing and Dicing Data in CF and SQL

Subquery: There are basically three types of subqueries are:

CS Week 10 - Page 1

Oracle Database 11g: SQL and PL/SQL Fundamentals

Using the Set Operators. Copyright 2006, Oracle. All rights reserved.

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

Database Management Systems,

Oracle Database SQL Basics

Practical Workbook Database Management Systems

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

Semantic Errors in Database Queries

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

Pivot Tables Motivation (1)

CSC Web Programming. Introduction to SQL

Oracle Database: SQL and PL/SQL Fundamentals NEW

Topic 8 Structured Query Language (SQL) : DML Part 2

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Real-World Performance Training SQL Introduction

Databases. Relational Model, Algebra and operations. How do we model and manipulate complex data structures inside a computer system? Until

Oracle Syllabus Course code-r10605 SQL

CS 275 Winter 2011 Problem Set 3

Some Basic Aggregate Functions FUNCTION OUTPUT The number of rows containing non-null values The maximum attribute value encountered in a given column

Tables From Existing Tables

Creating and Managing Tables Schedule: Timing Topic

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

An Introduction to Structured Query Language

2) SQL includes a data definition language, a data manipulation language, and SQL/Persistent stored modules. Answer: TRUE Diff: 2 Page Ref: 36

An Introduction to Structured Query Language

An Introduction to Structured Query Language

An Introduction to Structured Query Language

An Introduction to Structured Query Language

THE INDIAN COMMUNITY SCHOOL, KUWAIT

DUE: 9. Create a query that will return the average order total for all Global Fast Foods orders from January 1, 2002, to December 21, 2002.

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

FUN WITH ANALYTIC FUNCTIONS UTOUG TRAINING DAYS 2017

5 Integrity Constraints and Triggers

STIDistrict Query (Basic)

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

HKTA TANG HIN MEMORIAL SECONDARY SCHOOL SECONDARY 3 COMPUTER LITERACY. Name: ( ) Class: Date: Databases and Microsoft Access

SQL Data Query Language

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Full file at

CMP-3440 Database Systems

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Lab # 4 Hands-On. DDL and DML Advance SQL Statements Institute of Computer Science, University of Tartu, Estonia

II. Structured Query Language (SQL)

Part III. Data Modelling. Marc H. Scholl (DBIS, Uni KN) Information Management Winter 2007/08 1

Restricting and Sorting Data. Copyright 2004, Oracle. All rights reserved.

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

II. Structured Query Language (SQL)

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

RESTRICTING AND SORTING DATA

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

COMP 244 DATABASE CONCEPTS & APPLICATIONS

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Downloaded from

Create Rank Transformation in Informatica with example

Introduction to Computer Science and Business

Unit Assessment Guide

Greenplum SQL Class Outline

Creating Other Schema Objects

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

Tables and Volatile Tables

Practical Workbook Database Management Systems

Introduction to Oracle9i: SQL

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

Data Manipulation Language (DML)

Transcription:

GIFT Department of Computing Science CS-217: Database Systems Lab-4 Manual Reporting Aggregated Data using Group Functions V3.0 4/28/2016

Introduction to Lab-4 This lab further addresses functions. It focuses on obtaining summary information, such as averages, for group of rows. It discusses how to group rows in a table into smaller sets and how to specify the search criteria for group of rows. The main topics of this lab include: 1. What are group functions? 2. Types of group functions 3. Group functions syntax 4. Using group functions 5. Using the COUNT function 6. Group functions and NULL values 7. Creating groups of data (the GROUP BY clause) 8. GROUP BY clause syntax 9. Using the GROUP BY clause 10. Grouping by more than one column 11. Illegal queries using group functions 12. Excluding group results (the HAVING clause) 13. Nesting group functions 14. Practice SQL Statements 15. SOLUTIONS: Practice SQL Statements Objectives of this Lab At the end of this lab, students should be able to: Identify the available group functions Describe the use of group functions Group data by using the GROUP BY clause Include or exclude grouped rows by using the HAVING clause GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 1

1. What are Group Functions? Unlike single-row functions, group functions operate on sets of rows to give one result per group. These sets may be the whole table or the table split into groups. For example, what is the maximum salary in the employees table? 2. Types of Group Functions The group functions available are: AVG COUNT MAX MIN STDDEV SUM VARIANCE Each of the functions accepts an argument. The following table identifies the options that you can use in the syntax: Function Description AVG([DISTINCT ALL]n) Average value of n, ignoring null values COUNT({* [DISTINCT ALL]expr }) Number of rows, where expr evaluates to something other than null (count all selected rows using *, including duplicates and rows with nulls) GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 2

MAX([DISTINCT ALL]expr) MIN([DISTINCT ALL]expr) STDDEV([DISTINCT ALL]x) SUM([DISTINCT ALL]n) VARIANCE([DISTINCT ALL]x) Maximum value of expr, ignoring null values Minimum value of expr, ignoring null values Standard deviation of n, ignoring null values Sum values of n, ignoring null values Variance of n, ignoring null values 3. Group Functions Syntax Guidelines for Using Group Functions DISTINCT makes the function consider only nonduplicate values; ALL makes it consider every value, including duplicates. The default is ALL and therefore does not need to be specified. The data types for the functions with an expr argument may be CHAR, VARCHAR2, NUMBER, or DATE. All group functions ignore null values. To substitute a value for null values, use the NVL, NVL2, or COALESCE functions. 4. Using Group Functions You can use AVG, MIN, MAX, and SUM functions against columns that store numeric data. MIN and MAX functions can be used for any data type. Note: The DISTINCT clause is used to suppress counting of duplicate values in the functions. Examples of the usage of group functions: 1. SELECT AVG(sal), MAX(sal), MIN(sal), SUM(sal) ; 2. SELECT AVG(sal), MAX(sal), MIN(sal), SUM(sal) WHERE job LIKE %MAN ; 3. SELECT AVG(ALL sal) ; 4. SELECT AVG(DISTINCT sal) ; GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 3

5. SELECT MIN(hiredate), MAX(hiredate) ; The above query displays the most junior and most senior employees. 6. SELECT MIN(ALL hiredate), MAX(DISTINCT hiredate) ; Lab-4 Manual 2016 7. SELECT MIN(DISTINCT hiredate), MAX(DISTINCT hiredate) ; 8. SELECT MIN(ename), MAX(ename) ; The above query displays the employee name that is first and the employee name that is last in an alphabetized list of all employees. Note: The AVG, SUM, VARIANCE, and STDDEV functions can be used only with numeric data types. 5. Using the COUNT Function The COUNT function has three formats: COUNT( * ) COUNT(expr) COUNT(DISTINCT expr) COUNT( * ) returns the number of rows in a table that satisfy the criteria of the SELECT statement, including duplicate rows and rows containing null values in any of the columns. If a WHERE clause is included in the SELECT statement, COUNT( * ) returns the number of rows that satisfy the condition in the WHERE clause. In contrast, COUNT(expr)returns the number of non-null values in the column identified by expr. COUNT (DISTINCT expr) returns the number of unique, non-null values in the column identified by expr. Examples: 1. SELECT COUNT(*); 2. SELECT COUNT(*) WHERE deptno = 10; 3. SELECT COUNT(comm) ; 4. SELECT COUNT(comm) WHERE deptno = 30; GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 4

5. SELECT COUNT(deptno) ; 6. SELECT COUNT(DISTINCT deptno) ; 6. Group Functions and Null Values All group functions ignore null values in the column. For example, SELECT AVG(comm); In the above query, the average is calculated based only on the rows in the table where a valid value is stored in the COMM column. The average is calculated as the total commission paid to all employees divided by the number of employees receiving commission. The NVL function forces group functions to include null values. SELECT AVG(NVL(comm, 0)) ; The average is calculated based on all rows in the table, regardless of whether null values are stored in the COMM column. The average is calculated as the total commission that is paid to all employees divided by the total number of employees in the company. 7. Creating Groups of Data (the GROUP BY clause) Until now, all group functions have treated the table as one large group of information. At times, you need to divide the table of information into smaller groups. For example, display the average salary in EMP table for each department. This can be done using the GROUP BY clause. GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 5

8. GROUP BY Clause Syntax You can use the GROUP BY clause to divide the rows in a table into groups. You can then use the group functions to return summary information for each group. In the syntax, group_by_expression specifies columns whose values determine the basis for grouping rows. Guidelines: If you include a group function in a SELECT clause, you cannot select individual results as well, unless the individual column appears in the GROUP BY clause. You receive an error message if you fail to include the column in the GROUP BY clause. Using a WHERE clause, you can exclude rows before dividing them into groups. You must include the columns in the GROUP BY clause. You cannot use a column alias in the GROUP BY clause. By default, rows are sorted by ascending order of the columns included in the GROUP BY list. You can override this by using the ORDER BY clause. 9. Using the GROUP BY Clause When using the GROUP BY clause, make sure that all columns in the SELECT list that are not group functions are included in the GROUP BY clause. For Example, 1. SELECT deptno, AVG(sal) 2. SELECT AVG(sal) The GROUP BY column does not have to be in the SELECT list as in query-2 above. You can use the group function in the ORDER BY clause: SELECT deptno, AVG(sal) GROUP BY deptno ORDER BY AVG(sal); GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 6

10. Grouping by More Than One Column (Groups within Groups) Sometimes you need to see results for groups within groups. For example, display the results by adding up salaries in the EMP table for each job, grouped by department. 1. SELECT deptno Dept_ID, job Job, SUM(sal) GROUP BY deptno, job; 2. SELECT deptno Dept_ID, job Job, SUM(sal) GROUP BY deptno, job ORDER BY deptno; 11. Illegal Queries Using Group Functions Any column or expression in the SELECT list that is not an aggregate function must be in a GROUP BY clause. Failure to do so will result in an error. For example, SELECT deptno, COUNT(ename) ; You can correct the error by adding the GROUP BY clause: SELECT deptno, COUNT(ename) Also, the WHERE clause cannot be used to restrict groups. For example, the following query will result in an error: SELECT deptno, AVG(sal) WHERE AVG(sal) > 1500 You can correct this error by using the HAVING clause to restrict groups: SELECT deptno, AVG(sal) HAVING AVG(sal) > 1500 GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 7

12. Excluding Group Results (the HAVING clause) In the same way you use the WHERE clause to restrict rows that you select; you use the HAVING to restrict groups. For example, find the maximum salary per department when it is greater than $2000. By using the HAVING clause, we can restrict the groups on the basis of aggregate function. In the syntax, the group_condition is used to restrict the group of rows returned to those groups for which the specified condition is true. Returning to the above given example, SELECT deptno, MAX(sal) GROUP BY deptno HAVING MAX(sal) > 2000; Note: You can use a GROUP BY clause without using a group function in the SELECT list. For example, And also, SELECT deptno, AVG(sal) GROUP BY deptno HAVING MAX(sal) > 2000; SELECT job, SUM(sal) PAYROLL WHERE job NOT LIKE %MAN% GROUP BY job HAVING SUM(sal) > 2000 ORDER BY SUM(sal); GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 8

13. Nesting Group Functions Group functions can be nested to a depth of two. This example displays the maximum average salary. SELECT MAX(AVG(sal)) 14. Practice SQL Statements 1. Display the highest, lowest, sum, and average salary of all employees. Label the columns Maximum, Minimum, Sum, and Average respectively. Round your results to the nearest whole number. Place and run your SQL statement in a text file named lab_04_04.sql. 2. Modify the query in lab_04_04.sql to display the minimum, maximum, sum, and average salary for each job type. Resave lab_04_04.sql as lab_04_05.sql. Run the statement in lab_04_05.sql. 3. Write a query to display the number of people with the same job. 4. Determine the number of managers without listing them. Label the column Number of Managers. Hint: Use the MGR column to determine the number of managers. 5. Write a query that displays the difference between the highest and lowest salaries. Label the column DIFFERENCE. 6. Display the manager id and the salary of the lowest paid employee for that manager. Exclude anyone whose manager is not known. Exclude any groups where the minimum salary is less than $1500. Sort the output in descending order of salary. 7. Write a query to display each department s name, location, number of employees, and the average salary of all employees of that department. Label the columns Name, Location, Number of People, and Salary respectively. 8. Create a query that will display the total number of employees, and of that total, the number of employees hired in 1980, 1981, 1982, and 1983. Create appropriate column headings. 9. Create a matrix query to display the job, the salary for that job based on department number, and the total salary for that job, for departments 10, 20, 30, and 40, giving each column an appropriate heading. GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 9

15. SOLUTIONS: Practice SQL Statements GIFT Dept. of Computing Science CS-217: Database Systems (Lab) Page 10