SlideShare a Scribd company logo
Aggregating Data Using Group Functions
ObjectivesAfter completing this lesson, you should be able to do the following:Identify the available group functionsDescribe the use of group functionsGroup data using the GROUP BY clauseInclude or exclude grouped rows by using the HAVING clause
What Are Group Functions?Group functions operate on sets of rows to give one result per group.EMP   DEPTNO       SAL--------- ---------1024501050001013002080020110020300020300020297530160030285030125030950301500301250 MAX(SAL)---------5000“maximum    salary in the EMP table”
Types of Group FunctionsAVG COUNT MAXMIN STDDEV SUMVARIANCE
Using Group FunctionsSELECT	[column,] group_function(column)FROMtable[WHEREcondition][GROUP BYcolumn][ORDER BYcolumn];
Using AVG and SUM FunctionsYou can use AVG and SUM for numeric data.SQL> SELECTAVG(sal), MAX(sal),2MIN(sal), SUM(sal)3FROMemp4WHEREjob LIKE 'SALES%';AVG(SAL)  MAX(SAL)  MIN(SAL)  SUM(SAL)-------- --------- --------- ---------1400160012505600
Using MIN and MAX FunctionsYou can use MIN and MAX for any datatype.SQL> SELECTMIN(hiredate), MAX(hiredate)2  FROMemp;MIN(HIRED MAX(HIRED--------- ---------17-DEC-8012-JAN-83
Using the COUNT FunctionCOUNT(*) returns the number of rows in a table.SQL> SELECTCOUNT(*)2  FROMemp3  WHEREdeptno = 30; COUNT(*)---------6
Using the COUNT FunctionCOUNT(expr) returns the number of nonnull rows.SQL> SELECTCOUNT(comm)2  FROMemp3  WHEREdeptno = 30;COUNT(COMM)-----------4
Group Functions and Null ValuesGroup functions ignore null values in the column.SQL> SELECT AVG(comm)2  FROM   emp; AVG(COMM)---------550
Using the NVL Function with Group FunctionsThe NVL function forces group functions to include null values.SQL> SELECT AVG(NVL(comm,0))2  FROM   emp;AVG(NVL(COMM,0))----------------157.14286
2916.666721751566.6667Creating Groups of Data EMP   DEPTNO       SAL--------- ---------1024501050001013002080020110020300020300020297530160030285030125030950301500301250   DEPTNO  AVG(SAL)  ------- ---------102916.6667202175301566.6667“averagesalary in EMPtable for each department”
Creating Groups of Data: GROUP BY ClauseSELECTcolumn, group_function(column)FROMtable[WHEREcondition][GROUP BYgroup_by_expression][ORDER BYcolumn];Divide rows in a table into smaller groups by using the GROUP BY clause.
Using the GROUP BY Clause All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.SQL> SELECT   deptno, AVG(sal)2  FROM     emp3  GROUP BY deptno;   DEPTNO  AVG(SAL)--------- ---------102916.6667202175301566.6667
Using the GROUP BY Clause The GROUP BY column does not have to be in the SELECT list.SQL> SELECT   AVG(sal)2  FROM     emp3  GROUP BY deptno; AVG(SAL)--------- 2916.666721751566.6667
Grouping by More Than One ColumnEMP   DEPTNO JOB             SAL--------- --------- ---------10 MANAGER        245010 PRESIDENT      500010 CLERK          130020 CLERK           80020 CLERK          110020 ANALYST        300020 ANALYST        300020 MANAGER        297530 SALESMAN       160030 MANAGER        285030 SALESMAN       125030 CLERK           95030 SALESMAN       150030 SALESMAN       1250JOB        SUM(SAL)--------- ---------CLERK          1300MANAGER        2450PRESIDENT      5000ANALYST        6000CLERK          1900MANAGER        2975CLERK           950MANAGER        2850SALESMAN       5600DEPTNO--------101010202020303030“sum salaries in the EMP tablefor each job, grouped by department”
Using the GROUP BY Clause on Multiple ColumnsSQL> SELECT   deptno, job, sum(sal)2  FROM     emp3  GROUP BY deptno, job;   DEPTNO JOB        SUM(SAL)--------- --------- ---------10 CLERK          130010 MANAGER        245010 PRESIDENT      500020 ANALYST        600020 CLERK          1900...9 rows selected.
Illegal Queries Using Group FunctionsAny column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.SQL> SELECTdeptno, COUNT(ename)2  FROMemp;Column missing in the GROUP BY clauseSELECT deptno, COUNT(ename)       *ERROR at line 1:ORA-00937: not a single-group group function
Illegal Queries Using Group FunctionsYou cannot use the WHERE clause to restrict groups.You use the HAVING clause to restrict groups.SQL> SELECT deptno, AVG(sal)2  FROM emp3  WHERE AVG(sal) > 20004  GROUP BY deptno;Cannot use the WHERE clause            to restrict groupsWHERE AVG(sal) > 2000      *ERROR at line 3:ORA-00934: group function is not allowed here
Excluding Group Results500030002850EMP   DEPTNO       SAL--------- ---------1024501050001013002080020110020300020300020297530160030285030125030950301500301250“maximumsalaryper departmentgreater than$2900”   DEPTNO  MAX(SAL)--------- ---------105000203000
Excluding Group Results: HAVING ClauseUse the HAVING clause to restrict groupsRows are grouped.The group function is applied.Groups matching the HAVING clause are displayed.SELECTcolumn, group_functionFROMtable[WHEREcondition][GROUP BYgroup_by_expression][HAVINGgroup_condition][ORDER BYcolumn];
Using the HAVING ClauseSQL> SELECT   deptno, max(sal)2  FROM     emp3  GROUP BY deptno4  HAVING   max(sal)>2900;   DEPTNO  MAX(SAL)--------- ---------105000203000
Using the HAVING ClauseSQL> SELECT    job, SUM(sal) PAYROLL2  FROM      emp3  WHERE  job NOT LIKE 'SALES%'4  GROUP BY  job5  HAVING    SUM(sal)>50006  ORDER BY  SUM(sal);JOB         PAYROLL--------- ---------ANALYST        6000MANAGER        8275
Nesting Group FunctionsDisplay the maximum average salary. SQL> SELECT   max(avg(sal))2  FROM     emp3  GROUP BY deptno;MAX(AVG(SAL))-------------2916.6667
SummarySELECTcolumn, group_function(column)FROMtable[WHEREcondition][GROUP BYgroup_by_expression][HAVINGgroup_condition][ORDER BYcolumn];Order of evaluation of the clauses:WHERE clauseGROUP BY clauseHAVING clause
Practice OverviewShowing different queries that use group functionsGrouping by rows to achieve more than one resultExcluding groups by using the HAVING clause

More Related Content

What's hot (20)

PDF
Basic Sql Handouts
jhe04
 
DOCX
SQL-RDBMS Queries and Question Bank
Md Mudassir
 
PDF
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
Vibeesh CS
 
PDF
SQL Functions and Operators
Mohan Kumar.R
 
PDF
Oracle SQL 1 Day Tutorial
Chien Chung Shen
 
PPTX
Date and time functions in mysql
V.V.Vanniaperumal College for Women
 
PPTX
Mainframe jcl exec and dd statements part - 3
janaki ram
 
PPTX
Introduction to SQL
Mahir Haque
 
PPT
Cursores.ppt
Alan737817
 
PDF
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
DOC
Sql task
Nawaz Sk
 
PPT
Sql query [select, sub] 4
Dr. C.V. Suresh Babu
 
PDF
Triggers in plsql
Arun Sial
 
PPT
Introduction to-sql
BG Java EE Course
 
PPT
Restricting and Sorting Data - Oracle Data Base
Salman Memon
 
PPTX
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
DOC
SQL practice questions set - 2
Mohd Tousif
 
DOC
Sql queires
MohitKumar1985
 
PPT
Les07 (using the set operators)
Achmad Solichin
 
DOC
Best sql plsql material
pitchaiah yechuri
 
Basic Sql Handouts
jhe04
 
SQL-RDBMS Queries and Question Bank
Md Mudassir
 
Learning SAS With Example by Ron Cody :Chapter 16 to Chapter 20 Solution
Vibeesh CS
 
SQL Functions and Operators
Mohan Kumar.R
 
Oracle SQL 1 Day Tutorial
Chien Chung Shen
 
Date and time functions in mysql
V.V.Vanniaperumal College for Women
 
Mainframe jcl exec and dd statements part - 3
janaki ram
 
Introduction to SQL
Mahir Haque
 
Cursores.ppt
Alan737817
 
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
Sql task
Nawaz Sk
 
Sql query [select, sub] 4
Dr. C.V. Suresh Babu
 
Triggers in plsql
Arun Sial
 
Introduction to-sql
BG Java EE Course
 
Restricting and Sorting Data - Oracle Data Base
Salman Memon
 
DDL,DML,SQL Functions and Joins
Ashwin Dinoriya
 
SQL practice questions set - 2
Mohd Tousif
 
Sql queires
MohitKumar1985
 
Les07 (using the set operators)
Achmad Solichin
 
Best sql plsql material
pitchaiah yechuri
 

Viewers also liked (15)

PPTX
Les04 Displaying Data From Multiple Table
NETsolutions Asia: NSA – Thailand, Sripatum University: SPU
 
PPT
Human Capital Group Functions
Adora Ikwuemesi, FIIM, GPHR, PRINCE2, ACIPM
 
PPTX
Sets, functions and groups
Muhammad Adnan Ejaz
 
PPT
SQL WORKSHOP::Lecture 3
Umair Amjad
 
PPT
PDC+++ Module 1 Class 3
Academia de Permacultura Integral
 
PPT
Ob9 foundations of group behavior
haruno0205
 
PPTX
Group behaviour ppt
Lokesh Irabatti
 
PPT
Group Behavior
Sahil Mahajan
 
PPTX
Oracle Basics and Architecture
Sidney Chen
 
PPTX
Group behaviour ppt
Lokesh Irabatti
 
PPTX
Groups in Organisations and Group Dynamics.
Harshr1501
 
PPTX
ppt of group dynamics
Swati Gautam
 
Les04 Displaying Data From Multiple Table
NETsolutions Asia: NSA – Thailand, Sripatum University: SPU
 
Human Capital Group Functions
Adora Ikwuemesi, FIIM, GPHR, PRINCE2, ACIPM
 
Sets, functions and groups
Muhammad Adnan Ejaz
 
SQL WORKSHOP::Lecture 3
Umair Amjad
 
PDC+++ Module 1 Class 3
Academia de Permacultura Integral
 
Ob9 foundations of group behavior
haruno0205
 
Group behaviour ppt
Lokesh Irabatti
 
Group Behavior
Sahil Mahajan
 
Oracle Basics and Architecture
Sidney Chen
 
Group behaviour ppt
Lokesh Irabatti
 
Groups in Organisations and Group Dynamics.
Harshr1501
 
ppt of group dynamics
Swati Gautam
 
Ad

Similar to Les05 Aggregating Data Using Group Function (20)

PPT
SQL5.ppt
ayeshaasmat4
 
PPT
Sql5
Nargis Ehsan
 
PPT
SQL WORKSHOP::Lecture 5
Umair Amjad
 
PPT
Les05[1]Aggregating Data Using Group Functions
siavosh kaviani
 
PPT
Databasessanddataanalysis122222222222.ppt
siddigzain606
 
PPTX
Data Base Management Slides SQL with example
AmeerHamza708060
 
PDF
Sql group by clause
Vivek Singh
 
PPT
Aggregate Functions,Final
mukesh24pandey
 
PDF
Group by clause mod
Nitesh Singh
 
PPT
Les04
Sudharsan S
 
PPT
Les04
Achmad Solichin
 
PDF
Cube rollup slides
Saravanan Sevagan
 
PPT
Les01
Yousif Misbah
 
PPT
Les09
arnold 7490
 
DOC
ORACLE NOTES
Sachin Shukla
 
PPT
Les01
arnold 7490
 
PPT
Les05
Vijay Kumar
 
PPT
Les01-Oracle
suman1248
 
PDF
Sql having clause
Vivek Singh
 
SQL5.ppt
ayeshaasmat4
 
SQL WORKSHOP::Lecture 5
Umair Amjad
 
Les05[1]Aggregating Data Using Group Functions
siavosh kaviani
 
Databasessanddataanalysis122222222222.ppt
siddigzain606
 
Data Base Management Slides SQL with example
AmeerHamza708060
 
Sql group by clause
Vivek Singh
 
Aggregate Functions,Final
mukesh24pandey
 
Group by clause mod
Nitesh Singh
 
Cube rollup slides
Saravanan Sevagan
 
ORACLE NOTES
Sachin Shukla
 
Les01-Oracle
suman1248
 
Sql having clause
Vivek Singh
 
Ad

More from NETsolutions Asia: NSA – Thailand, Sripatum University: SPU (6)

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Digital Circuits, important subject in CS
contactparinay1
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 

Les05 Aggregating Data Using Group Function

  • 1. Aggregating Data Using Group Functions
  • 2. ObjectivesAfter completing this lesson, you should be able to do the following:Identify the available group functionsDescribe the use of group functionsGroup data using the GROUP BY clauseInclude or exclude grouped rows by using the HAVING clause
  • 3. What Are Group Functions?Group functions operate on sets of rows to give one result per group.EMP DEPTNO SAL--------- ---------1024501050001013002080020110020300020300020297530160030285030125030950301500301250 MAX(SAL)---------5000“maximum salary in the EMP table”
  • 4. Types of Group FunctionsAVG COUNT MAXMIN STDDEV SUMVARIANCE
  • 5. Using Group FunctionsSELECT [column,] group_function(column)FROMtable[WHEREcondition][GROUP BYcolumn][ORDER BYcolumn];
  • 6. Using AVG and SUM FunctionsYou can use AVG and SUM for numeric data.SQL> SELECTAVG(sal), MAX(sal),2MIN(sal), SUM(sal)3FROMemp4WHEREjob LIKE 'SALES%';AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)-------- --------- --------- ---------1400160012505600
  • 7. Using MIN and MAX FunctionsYou can use MIN and MAX for any datatype.SQL> SELECTMIN(hiredate), MAX(hiredate)2 FROMemp;MIN(HIRED MAX(HIRED--------- ---------17-DEC-8012-JAN-83
  • 8. Using the COUNT FunctionCOUNT(*) returns the number of rows in a table.SQL> SELECTCOUNT(*)2 FROMemp3 WHEREdeptno = 30; COUNT(*)---------6
  • 9. Using the COUNT FunctionCOUNT(expr) returns the number of nonnull rows.SQL> SELECTCOUNT(comm)2 FROMemp3 WHEREdeptno = 30;COUNT(COMM)-----------4
  • 10. Group Functions and Null ValuesGroup functions ignore null values in the column.SQL> SELECT AVG(comm)2 FROM emp; AVG(COMM)---------550
  • 11. Using the NVL Function with Group FunctionsThe NVL function forces group functions to include null values.SQL> SELECT AVG(NVL(comm,0))2 FROM emp;AVG(NVL(COMM,0))----------------157.14286
  • 12. 2916.666721751566.6667Creating Groups of Data EMP DEPTNO SAL--------- ---------1024501050001013002080020110020300020300020297530160030285030125030950301500301250 DEPTNO AVG(SAL) ------- ---------102916.6667202175301566.6667“averagesalary in EMPtable for each department”
  • 13. Creating Groups of Data: GROUP BY ClauseSELECTcolumn, group_function(column)FROMtable[WHEREcondition][GROUP BYgroup_by_expression][ORDER BYcolumn];Divide rows in a table into smaller groups by using the GROUP BY clause.
  • 14. Using the GROUP BY Clause All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.SQL> SELECT deptno, AVG(sal)2 FROM emp3 GROUP BY deptno; DEPTNO AVG(SAL)--------- ---------102916.6667202175301566.6667
  • 15. Using the GROUP BY Clause The GROUP BY column does not have to be in the SELECT list.SQL> SELECT AVG(sal)2 FROM emp3 GROUP BY deptno; AVG(SAL)--------- 2916.666721751566.6667
  • 16. Grouping by More Than One ColumnEMP DEPTNO JOB SAL--------- --------- ---------10 MANAGER 245010 PRESIDENT 500010 CLERK 130020 CLERK 80020 CLERK 110020 ANALYST 300020 ANALYST 300020 MANAGER 297530 SALESMAN 160030 MANAGER 285030 SALESMAN 125030 CLERK 95030 SALESMAN 150030 SALESMAN 1250JOB SUM(SAL)--------- ---------CLERK 1300MANAGER 2450PRESIDENT 5000ANALYST 6000CLERK 1900MANAGER 2975CLERK 950MANAGER 2850SALESMAN 5600DEPTNO--------101010202020303030“sum salaries in the EMP tablefor each job, grouped by department”
  • 17. Using the GROUP BY Clause on Multiple ColumnsSQL> SELECT deptno, job, sum(sal)2 FROM emp3 GROUP BY deptno, job; DEPTNO JOB SUM(SAL)--------- --------- ---------10 CLERK 130010 MANAGER 245010 PRESIDENT 500020 ANALYST 600020 CLERK 1900...9 rows selected.
  • 18. Illegal Queries Using Group FunctionsAny column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.SQL> SELECTdeptno, COUNT(ename)2 FROMemp;Column missing in the GROUP BY clauseSELECT deptno, COUNT(ename) *ERROR at line 1:ORA-00937: not a single-group group function
  • 19. Illegal Queries Using Group FunctionsYou cannot use the WHERE clause to restrict groups.You use the HAVING clause to restrict groups.SQL> SELECT deptno, AVG(sal)2 FROM emp3 WHERE AVG(sal) > 20004 GROUP BY deptno;Cannot use the WHERE clause to restrict groupsWHERE AVG(sal) > 2000 *ERROR at line 3:ORA-00934: group function is not allowed here
  • 20. Excluding Group Results500030002850EMP DEPTNO SAL--------- ---------1024501050001013002080020110020300020300020297530160030285030125030950301500301250“maximumsalaryper departmentgreater than$2900” DEPTNO MAX(SAL)--------- ---------105000203000
  • 21. Excluding Group Results: HAVING ClauseUse the HAVING clause to restrict groupsRows are grouped.The group function is applied.Groups matching the HAVING clause are displayed.SELECTcolumn, group_functionFROMtable[WHEREcondition][GROUP BYgroup_by_expression][HAVINGgroup_condition][ORDER BYcolumn];
  • 22. Using the HAVING ClauseSQL> SELECT deptno, max(sal)2 FROM emp3 GROUP BY deptno4 HAVING max(sal)>2900; DEPTNO MAX(SAL)--------- ---------105000203000
  • 23. Using the HAVING ClauseSQL> SELECT job, SUM(sal) PAYROLL2 FROM emp3 WHERE job NOT LIKE 'SALES%'4 GROUP BY job5 HAVING SUM(sal)>50006 ORDER BY SUM(sal);JOB PAYROLL--------- ---------ANALYST 6000MANAGER 8275
  • 24. Nesting Group FunctionsDisplay the maximum average salary. SQL> SELECT max(avg(sal))2 FROM emp3 GROUP BY deptno;MAX(AVG(SAL))-------------2916.6667
  • 25. SummarySELECTcolumn, group_function(column)FROMtable[WHEREcondition][GROUP BYgroup_by_expression][HAVINGgroup_condition][ORDER BYcolumn];Order of evaluation of the clauses:WHERE clauseGROUP BY clauseHAVING clause
  • 26. Practice OverviewShowing different queries that use group functionsGrouping by rows to achieve more than one resultExcluding groups by using the HAVING clause