Group functions operate on sets of rows to give one result per group. Common group functions include COUNT, SUM, AVG, MIN, and MAX. The GROUP BY clause is used to divide rows into groups and the HAVING clause excludes groups based on a condition. Nesting group functions allows analyzing groups of groups, like finding the maximum of several averages.
This document discusses how to aggregate data using group functions in SQL. It describes the available group functions like AVG, COUNT, MAX, MIN, SUM, and how to use them. It explains how to group data using the GROUP BY clause and include or exclude grouped rows using the HAVING clause. Examples are provided to illustrate grouping data by one or more columns and restricting groups with the HAVING clause.
Subqueries allow queries to be nested within other queries. They can return either single rows or multiple rows. Single-row subqueries use comparison operators like = or >, while multiple-row subqueries use operators like IN, ANY, or ALL. Subqueries execute first before the outer or main query uses the results. This allows the main query to filter or compare based on unknown values from the subquery.
Group functions operate on sets of rows to give one result per group. Some key points covered in the document include:
1. Group functions like AVG, COUNT, MAX, MIN, SUM allow aggregating data across rows grouped by columns like department.
2. The GROUP BY clause is used to divide rows into groups and column(s) in the SELECT that are not aggregate functions must be in the GROUP BY.
3. The HAVING clause is used to filter groups based on conditions with aggregate functions and comes after GROUP BY.
This document discusses views in Oracle databases. It defines a view as a virtual table derived from one or more underlying base tables or other views. The document covers how to create simple and complex views, modify view definitions, perform DML operations on views, and remove views. Key points include that views allow restricting access, simplifying queries, and presenting different perspectives of the same data without affecting the base tables.
This document discusses how to restrict and sort data retrieved by SQL queries. It covers limiting rows using the WHERE clause and comparison operators, and sorting rows using the ORDER BY clause. Examples are provided for each clause and operator to filter rows by conditions and sort the output in ascending or descending order on one or multiple columns. Parentheses can be used to override the default order of operation precedence.
The document provides an overview of basic SQL statements and capabilities. It discusses using SELECT statements to project columns, select rows, and join tables. It also covers arithmetic expressions, column aliases, concatenation, and eliminating duplicate rows. SQL statements are executed through the SQL*Plus environment, which allows editing, saving, and running SQL code and commands.
This document discusses how to limit and sort data retrieved from a database table using SQL queries. It covers using the WHERE clause to restrict rows by conditions, comparison operators like = and BETWEEN, logical operators like AND and OR, and the ORDER BY clause to sort rows in ascending or descending order based on one or more columns. Examples are provided for each technique.
This document discusses techniques for joining data from multiple database tables. It covers equijoins to retrieve matching records between tables, non-equijoins to retrieve records with non-equal conditions, outer joins to include non-matching records, and self joins to join a table to itself. Examples are provided to demonstrate how to write SQL statements to perform each type of join and include additional conditions.
This document discusses how to aggregate data using group functions in SQL. It describes the available group functions like AVG, COUNT, MAX, MIN, SUM, and how to use them. It explains how to group data using the GROUP BY clause and include or exclude grouped rows using the HAVING clause. Examples are provided to illustrate grouping data by one or more columns and restricting groups with the HAVING clause.
Subqueries allow queries to be nested within other queries. They can return either single rows or multiple rows. Single-row subqueries use comparison operators like = or >, while multiple-row subqueries use operators like IN, ANY, or ALL. Subqueries execute first before the outer or main query uses the results. This allows the main query to filter or compare based on unknown values from the subquery.
Group functions operate on sets of rows to give one result per group. Some key points covered in the document include:
1. Group functions like AVG, COUNT, MAX, MIN, SUM allow aggregating data across rows grouped by columns like department.
2. The GROUP BY clause is used to divide rows into groups and column(s) in the SELECT that are not aggregate functions must be in the GROUP BY.
3. The HAVING clause is used to filter groups based on conditions with aggregate functions and comes after GROUP BY.
This document discusses views in Oracle databases. It defines a view as a virtual table derived from one or more underlying base tables or other views. The document covers how to create simple and complex views, modify view definitions, perform DML operations on views, and remove views. Key points include that views allow restricting access, simplifying queries, and presenting different perspectives of the same data without affecting the base tables.
This document discusses how to restrict and sort data retrieved by SQL queries. It covers limiting rows using the WHERE clause and comparison operators, and sorting rows using the ORDER BY clause. Examples are provided for each clause and operator to filter rows by conditions and sort the output in ascending or descending order on one or multiple columns. Parentheses can be used to override the default order of operation precedence.
The document provides an overview of basic SQL statements and capabilities. It discusses using SELECT statements to project columns, select rows, and join tables. It also covers arithmetic expressions, column aliases, concatenation, and eliminating duplicate rows. SQL statements are executed through the SQL*Plus environment, which allows editing, saving, and running SQL code and commands.
This document discusses how to limit and sort data retrieved from a database table using SQL queries. It covers using the WHERE clause to restrict rows by conditions, comparison operators like = and BETWEEN, logical operators like AND and OR, and the ORDER BY clause to sort rows in ascending or descending order based on one or more columns. Examples are provided for each technique.
This document discusses techniques for joining data from multiple database tables. It covers equijoins to retrieve matching records between tables, non-equijoins to retrieve records with non-equal conditions, outer joins to include non-matching records, and self joins to join a table to itself. Examples are provided to demonstrate how to write SQL statements to perform each type of join and include additional conditions.
Single-row functions can manipulate data items, accept arguments and return one value, and act on each row returned. There are various types of single-row functions including character, number, date, and conversion functions. Character functions manipulate character strings, number functions perform calculations, and date functions modify date formats. Functions allow data to be formatted, calculated, and converted as needed for different queries and outputs.
The document discusses the GROUP BY clause in SQL, which groups or categorizes data in a table into smaller groups based on specified column(s). Group functions like SUM, COUNT, MAX, MIN can then return summary information for each group. The GROUP BY clause is used with SELECT statements to group data and apply aggregate functions to each group. It explains how to group data by single or multiple columns, and restrict groups using the HAVING clause.
This document describes various single-row functions in SQL that can manipulate or modify data. It discusses character, number, date, and conversion functions and provides examples of how to use functions like TO_CHAR, TO_NUMBER, ROUND, TRUNC, and DECODE in SELECT statements. Common uses of functions include performing calculations, formatting output, converting data types, and conditional processing of data. Nesting functions allows multiple operations to be applied sequentially.
This document provides an overview of basic SQL statements and SQL*Plus commands. It covers capabilities of SELECT statements, executing a basic SELECT statement, writing SQL statements, selecting specific columns, using arithmetic expressions and operators, defining aliases and literals, eliminating duplicate rows, and interacting with SQL*Plus through commands like editing, saving, and running SQL statements.
The ALTER command in MySQL is used to modify the structure of existing tables. It allows you to add, drop, or modify columns, change the data type of columns, rename tables, and change the table type. Some key things the ALTER command allows you to do include:
1. Add or drop columns from a table.
2. Modify column definitions by changing the data type, default value, nullability, or length of a column.
3. Change the name of a table or rename columns.
4. Change the table type, such as converting between InnoDB and MyISAM.
The ALTER table command in SQL is used to modify the structure of an existing table. It can be used to add new columns, delete columns, change column sizes or data types, and add integrity constraints. Some key uses of ALTER table include adding a new column using the ADD command, modifying column properties like data type or default value using the MODIFY command, and changing the structure of a table.
The HAVING clause is used to filter data based on group functions, similar to a WHERE clause but for use with aggregate functions. Group functions like SUM cannot be used in a WHERE clause but can be used in a HAVING clause. An example SQL query uses a HAVING clause to select departments where the total salary paid is over $25,000. When used together, the WHERE clause is processed first before rows are grouped by the GROUP BY clause and then conditions in the HAVING clause are applied to the grouped rows.
This document discusses data manipulation in Oracle databases. It describes how to insert, update, and delete rows from tables using DML statements like INSERT, UPDATE, and DELETE. It also covers transaction management using COMMIT, ROLLBACK, and SAVEPOINT statements to control when changes are committed to the database or rolled back. Key aspects covered include inserting new rows, updating and deleting specific rows or all rows, and handling integrity constraints and transactions.
This document describes views in an Oracle database. It defines what a view is, explains why they are used to restrict access, simplify queries, and provide different perspectives on the same data. It covers how to create simple and complex views, retrieve data from views, modify data through views depending on their definition, and remove views. The key points are that views allow logical abstraction of data without changing the physical storage and have benefits for access control, query optimization, and data independence.
This document discusses relational databases and the Oracle implementation. It introduces relational database concepts like tables, relations, keys and SQL. It describes how Oracle uses SQL and the PL/SQL programming language to interact with and manage data in a relational database management system. PL/SQL allows embedding SQL statements in procedural code blocks for data manipulation and queries.
This document discusses restricting and sorting data in SQL queries. It describes how to limit rows returned using a WHERE clause and comparison operators. It also explains how to sort rows using an ORDER BY clause, including sorting in ascending and descending order and by multiple columns. Logical operators, precedence rules, and NULL handling are also covered.
A view allows users to access data from one or more tables in a database. Views can simplify queries, restrict access to data, and present alternative perspectives of the underlying data. The document describes how to create simple and complex views, add constraints to views, modify data through views, and remove views from the database. Views provide a way to access data without allowing direct modification of the base tables.
This document provides an overview of basic SQL statements including:
- Executing a basic SELECT statement to retrieve data from tables
- Using functions like SELECT, FROM, and DISTINCT to retrieve specific columns and eliminate duplicates
- Performing calculations on columns using arithmetic operators
- Renaming columns with aliases and concatenating columns
- Describing the structure of tables using the DESCRIBE command
The goal is to learn fundamental SQL skills like selecting, calculating, aliasing columns, and viewing table definitions.
The document describes three types of user-defined functions in SQL Server: 1) Scalar functions that return a single value, 2) Inline table valued functions that return a table object, and 3) Multi-statement table valued functions that explicitly define the structure of the table to return. Examples are provided for each type of function, including how to create, modify, and execute the functions. Triggers are also discussed, with an example provided of an AFTER UPDATE trigger that inserts old records from the updated table into a second table.
The document discusses how to create and manage database tables. Key topics covered include using CREATE TABLE to define table structure, ALTER TABLE to modify tables, DROP TABLE to remove tables, and TRUNCATE TABLE to delete all rows. Datatypes, naming conventions, adding comments, and joining tables with subqueries are also summarized.
This document discusses various ways to customize SQL*Plus and produce more readable output, including:
1) Using substitution variables to prompt for input and dynamically alter queries, reports, and file names.
2) Defining variables with DEFINE and ACCEPT and passing values between SQL statements.
3) Customizing the SQL*Plus environment with SET commands and verifying settings with SHOW.
The document discusses data manipulation language (DML) statements in SQL. It describes how to insert rows into a table using INSERT, update rows using UPDATE, and delete rows from a table using DELETE. It also covers transaction control using COMMIT to save changes permanently and ROLLBACK to undo pending changes back to a savepoint.
This document discusses restricting and sorting data in SQL queries. It covers limiting rows using the WHERE clause with various operators like comparison, logical, BETWEEN, IN, LIKE and IS NULL. It also covers sorting result rows using the ORDER BY clause, including sorting in ascending and descending order and by multiple columns. The overall goal is to select specific data rows and control the order of rows displayed in the results.
Constraints enforce rules at the table level to maintain data integrity. The main types of constraints are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK. Constraints can be created at table creation or added later using ALTER TABLE. Constraint information is stored in data dictionary views like USER_CONSTRAINTS and USER_CONS_COLUMNS which can be queried.
1. The document discusses using ROLLUP and CUBE operations to produce subtotal and cross-tabulation values from grouped data.
2. It also covers using the GROUPING function to identify rows created by ROLLUP or CUBE, and using GROUPING SETS to define multiple groupings in a single query for improved efficiency.
3. The techniques described include composite columns, concatenated grouping sets, and combining GROUP BY expressions in various ways.
The document discusses endangered species and ecosystems. It defines species and explains that natural ecosystems are sustainable as they provide habitats for species to live. However, human activities like changing the environment can lead to unsustainable ecosystems, forcing species to leave their habitats and potentially become extinct if they cannot find new ones. A species is considered extinct if it has not been seen in the wild for over 50 years. The document notes that over 125 Australian plant and animal species have gone extinct in the past 200 years due to hunting and environmental changes, and species are under threat around the world like in Sumatra where rainforest destruction has endangered elephants, tigers, rhinos and orangutans.
The document discusses different types of bikes including big bikes, naked bikes, spoqt bikes, touqing bikes, and choppeq bikes. No other details are provided about the various bike types.
Single-row functions can manipulate data items, accept arguments and return one value, and act on each row returned. There are various types of single-row functions including character, number, date, and conversion functions. Character functions manipulate character strings, number functions perform calculations, and date functions modify date formats. Functions allow data to be formatted, calculated, and converted as needed for different queries and outputs.
The document discusses the GROUP BY clause in SQL, which groups or categorizes data in a table into smaller groups based on specified column(s). Group functions like SUM, COUNT, MAX, MIN can then return summary information for each group. The GROUP BY clause is used with SELECT statements to group data and apply aggregate functions to each group. It explains how to group data by single or multiple columns, and restrict groups using the HAVING clause.
This document describes various single-row functions in SQL that can manipulate or modify data. It discusses character, number, date, and conversion functions and provides examples of how to use functions like TO_CHAR, TO_NUMBER, ROUND, TRUNC, and DECODE in SELECT statements. Common uses of functions include performing calculations, formatting output, converting data types, and conditional processing of data. Nesting functions allows multiple operations to be applied sequentially.
This document provides an overview of basic SQL statements and SQL*Plus commands. It covers capabilities of SELECT statements, executing a basic SELECT statement, writing SQL statements, selecting specific columns, using arithmetic expressions and operators, defining aliases and literals, eliminating duplicate rows, and interacting with SQL*Plus through commands like editing, saving, and running SQL statements.
The ALTER command in MySQL is used to modify the structure of existing tables. It allows you to add, drop, or modify columns, change the data type of columns, rename tables, and change the table type. Some key things the ALTER command allows you to do include:
1. Add or drop columns from a table.
2. Modify column definitions by changing the data type, default value, nullability, or length of a column.
3. Change the name of a table or rename columns.
4. Change the table type, such as converting between InnoDB and MyISAM.
The ALTER table command in SQL is used to modify the structure of an existing table. It can be used to add new columns, delete columns, change column sizes or data types, and add integrity constraints. Some key uses of ALTER table include adding a new column using the ADD command, modifying column properties like data type or default value using the MODIFY command, and changing the structure of a table.
The HAVING clause is used to filter data based on group functions, similar to a WHERE clause but for use with aggregate functions. Group functions like SUM cannot be used in a WHERE clause but can be used in a HAVING clause. An example SQL query uses a HAVING clause to select departments where the total salary paid is over $25,000. When used together, the WHERE clause is processed first before rows are grouped by the GROUP BY clause and then conditions in the HAVING clause are applied to the grouped rows.
This document discusses data manipulation in Oracle databases. It describes how to insert, update, and delete rows from tables using DML statements like INSERT, UPDATE, and DELETE. It also covers transaction management using COMMIT, ROLLBACK, and SAVEPOINT statements to control when changes are committed to the database or rolled back. Key aspects covered include inserting new rows, updating and deleting specific rows or all rows, and handling integrity constraints and transactions.
This document describes views in an Oracle database. It defines what a view is, explains why they are used to restrict access, simplify queries, and provide different perspectives on the same data. It covers how to create simple and complex views, retrieve data from views, modify data through views depending on their definition, and remove views. The key points are that views allow logical abstraction of data without changing the physical storage and have benefits for access control, query optimization, and data independence.
This document discusses relational databases and the Oracle implementation. It introduces relational database concepts like tables, relations, keys and SQL. It describes how Oracle uses SQL and the PL/SQL programming language to interact with and manage data in a relational database management system. PL/SQL allows embedding SQL statements in procedural code blocks for data manipulation and queries.
This document discusses restricting and sorting data in SQL queries. It describes how to limit rows returned using a WHERE clause and comparison operators. It also explains how to sort rows using an ORDER BY clause, including sorting in ascending and descending order and by multiple columns. Logical operators, precedence rules, and NULL handling are also covered.
A view allows users to access data from one or more tables in a database. Views can simplify queries, restrict access to data, and present alternative perspectives of the underlying data. The document describes how to create simple and complex views, add constraints to views, modify data through views, and remove views from the database. Views provide a way to access data without allowing direct modification of the base tables.
This document provides an overview of basic SQL statements including:
- Executing a basic SELECT statement to retrieve data from tables
- Using functions like SELECT, FROM, and DISTINCT to retrieve specific columns and eliminate duplicates
- Performing calculations on columns using arithmetic operators
- Renaming columns with aliases and concatenating columns
- Describing the structure of tables using the DESCRIBE command
The goal is to learn fundamental SQL skills like selecting, calculating, aliasing columns, and viewing table definitions.
The document describes three types of user-defined functions in SQL Server: 1) Scalar functions that return a single value, 2) Inline table valued functions that return a table object, and 3) Multi-statement table valued functions that explicitly define the structure of the table to return. Examples are provided for each type of function, including how to create, modify, and execute the functions. Triggers are also discussed, with an example provided of an AFTER UPDATE trigger that inserts old records from the updated table into a second table.
The document discusses how to create and manage database tables. Key topics covered include using CREATE TABLE to define table structure, ALTER TABLE to modify tables, DROP TABLE to remove tables, and TRUNCATE TABLE to delete all rows. Datatypes, naming conventions, adding comments, and joining tables with subqueries are also summarized.
This document discusses various ways to customize SQL*Plus and produce more readable output, including:
1) Using substitution variables to prompt for input and dynamically alter queries, reports, and file names.
2) Defining variables with DEFINE and ACCEPT and passing values between SQL statements.
3) Customizing the SQL*Plus environment with SET commands and verifying settings with SHOW.
The document discusses data manipulation language (DML) statements in SQL. It describes how to insert rows into a table using INSERT, update rows using UPDATE, and delete rows from a table using DELETE. It also covers transaction control using COMMIT to save changes permanently and ROLLBACK to undo pending changes back to a savepoint.
This document discusses restricting and sorting data in SQL queries. It covers limiting rows using the WHERE clause with various operators like comparison, logical, BETWEEN, IN, LIKE and IS NULL. It also covers sorting result rows using the ORDER BY clause, including sorting in ascending and descending order and by multiple columns. The overall goal is to select specific data rows and control the order of rows displayed in the results.
Constraints enforce rules at the table level to maintain data integrity. The main types of constraints are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK. Constraints can be created at table creation or added later using ALTER TABLE. Constraint information is stored in data dictionary views like USER_CONSTRAINTS and USER_CONS_COLUMNS which can be queried.
1. The document discusses using ROLLUP and CUBE operations to produce subtotal and cross-tabulation values from grouped data.
2. It also covers using the GROUPING function to identify rows created by ROLLUP or CUBE, and using GROUPING SETS to define multiple groupings in a single query for improved efficiency.
3. The techniques described include composite columns, concatenated grouping sets, and combining GROUP BY expressions in various ways.
The document discusses endangered species and ecosystems. It defines species and explains that natural ecosystems are sustainable as they provide habitats for species to live. However, human activities like changing the environment can lead to unsustainable ecosystems, forcing species to leave their habitats and potentially become extinct if they cannot find new ones. A species is considered extinct if it has not been seen in the wild for over 50 years. The document notes that over 125 Australian plant and animal species have gone extinct in the past 200 years due to hunting and environmental changes, and species are under threat around the world like in Sumatra where rainforest destruction has endangered elephants, tigers, rhinos and orangutans.
The document discusses different types of bikes including big bikes, naked bikes, spoqt bikes, touqing bikes, and choppeq bikes. No other details are provided about the various bike types.
El documento describe los diferentes aspectos del desarrollo de videojuegos, incluyendo las perspectivas de desarrollo, las diferencias entre juegos, juguetes y simulaciones, los tipos y géneros de juegos, la estructura y producción de juegos, y los roles en el diseño, programación, arte y audio. También analiza ejemplos concretos del desarrollo de juegos como Gears of War y Grabbity.
Efecto Studios is a videogame developer company that creates games for Windows PC, consoles, and mobile devices using engines like Unreal and Unity. They have developed games like Monster Madness: Battle for Suburbia and Lucha Libre AAA: Heroes del Ring. Efecto Studios offers full game development services including concept, art, and programming and aims to deliver high quality, innovative products to clients.
The document describes the electronic control system for a pump. It details that the controller receives input signals like engine speed and pressure, processes them, and sends output signals to control components like solenoids. It also explains the different working modes and how the system controls both the pump and engine to improve power and fuel efficiency. Modes can be selected to optimize for different work conditions. The document outlines what happens if the controller fails and how switches can bypass it to maintain basic pump functions.
The document discusses quicksort and partition algorithms for sorting arrays. Quicksort works by recursively dividing an array into smaller sub-arrays by partitioning them based on a pivot value and sorting them. The partition algorithm divides an array into two partitions based on element values relative to the pivot. The performance of quicksort depends on how balanced the partitions are at each step.
Redland City Council in Australia leveraged its existing Microsoft Citizen Services Platform to develop a graffiti management application. The application allows citizens and council workers to report graffiti using smartphones, photos, and maps. It provides automated updates on graffiti removal. This has improved community engagement and simplified processes for managing graffiti reports and removal. The application was developed quickly using the Citizen Services Platform at low cost, demonstrating the benefits of the platform for developing additional citizen-focused applications.
This chapter discusses entity relationship (E-R) modeling and its purpose in database design. It covers the key components of E-R modeling including entities, attributes, relationships and how they are defined and refined. The chapter also explains conceptual, internal and external data models and how E-R diagrams represent the conceptual view through entities, attributes, and relationships. Generalization hierarchies and the iterative process for developing E-R diagrams are also summarized.
The document discusses control valves used in hydraulic excavators. It describes the components of the control valve including jet sensors that detect oil flow, relief valves, and valves for straight travel, arm throttle, and swing priority. The jet sensors measure pressure differences to detect when levers are operated. The relief valve maintains maximum work pressure. The straight travel, arm throttle, and swing priority valves control oil flow to prevent deviation during different machine operations.
This document describes a variable displacement piston pump. It has two pumps that can operate independently or together, with a maximum displacement of 112cc per pump. The pumps are controlled by LS and PC valves to vary the flow based on load conditions. The LS valve senses load and controls pump discharge, while the PC valve controls pump flow to match engine horsepower. Solenoids apply control pressures to the LS and PC valves to regulate pump flow.
The relational database model chapter 2Nargis Ehsan
The document discusses the relational database model and its key concepts. It describes how the model focuses on logical representation of data using tables rather than physical storage. The main concepts covered are entities, attributes, tables, rows and columns, primary keys, foreign keys, and integrity rules. It also explains the common relational operators like select, project, join, union, intersect, difference, and product and provides examples of how they manipulate and combine table data. Finally, it discusses data dictionaries, system catalogs, and their role in metadata management.
This short document contains a link and encourages the reader to click on it to access or obtain something. No other context is provided about what would be accessed or obtained by clicking the link.
This short document contains a link and encourages the reader to click on it to access or obtain something. No other context is provided about what would be received by clicking the link or any other details.
This short document contains a link and encourages the reader to click on it to access or obtain something. No other context is provided about what would be accessed or obtained by clicking the link.
This document discusses how to aggregate data using group functions in SQL. It describes various group functions like AVG, COUNT, MAX, MIN, and SUM. It explains how to use the GROUP BY clause to group data by one or more columns and produce aggregate results for each group. It also covers using the HAVING clause to filter groups based on aggregate conditions.
Les05[1]Aggregating Data Using Group Functionssiavosh kaviani
This document discusses how to use group functions in SQL to aggregate data and group rows together. It describes the available group functions like COUNT, AVG, MAX, MIN, and SUM. It explains how to use the GROUP BY clause to divide rows into groups and the HAVING clause to filter groups. It also shows examples of grouping data by department to find average salaries and summing salaries by job and department.
The document provides an overview of Data Query Language (DQL) syntax for SELECT statements including:
- Selecting columns from tables
- Using column aliases
- Filtering rows with the WHERE clause
- Working with NULL values
- Sorting results with the ORDER BY clause
- Grouping rows with the GROUP BY clause and aggregate functions
- Filtering groups with the HAVING clause
- Sorting on multiple columns
- Nested subqueries
This document discusses SQL group functions and how to summarize aggregated data from tables. It covers:
1) The main group functions - AVG, COUNT, MAX, MIN, SUM - and how to use them to aggregate numeric, character and date fields.
2) Using the GROUP BY clause to divide rows into groups and return aggregate results per group. Columns in the SELECT must be in the GROUP BY or be aggregate functions.
3) Applying the HAVING clause to restrict groups based on aggregate results, after rows are grouped and aggregate functions applied. HAVING cannot be used in the WHERE clause.
This document discusses how to use group functions in SQL to aggregate data and summarize information. Group functions such as MAX, MIN, SUM, AVG, COUNT operate on sets of rows and return one result per group. The GROUP BY clause is used to divide rows into groups, and the HAVING clause filters groups. Examples demonstrate finding minimum/maximum salaries, averages grouped by department, and sums grouped by multiple columns using functions like ROLLUP and CUBE.
This document discusses SQL group functions and how to summarize aggregated data from tables. It covers:
1) The main group functions - AVG, COUNT, MAX, MIN, SUM - and how to use them to aggregate data from columns.
2) Using the GROUP BY clause to divide rows into groups and apply aggregate functions per group.
3) Using the HAVING clause to restrict groups based on aggregate conditions, since aggregates cannot be used in the WHERE clause.
This document discusses how to aggregate and group data using SQL functions. It covers various group functions like COUNT, MAX, MIN, AVG, and SUM. It explains how to use the GROUP BY clause to group rows by one or more columns and produce an aggregate result per group. It also explains how to use the HAVING clause to filter groups based on aggregate conditions.
Group functions operate on sets of rows to aggregate data and return a single result per group. Common group functions include AVG, COUNT, MAX, MIN, and SUM. The GROUP BY clause is used to split rows into groups and is required when non-aggregate columns are selected. The HAVING clause allows filtering groups based on conditions and is analogous to the WHERE clause for rows. Nesting group functions allows aggregating aggregates, like finding the maximum average salary.
The SQL GROUP BY clause is used to retrieve data grouped by one or more columns. It is often used with aggregate functions like SUM to calculate totals for each group. For example, to find the total salary for each department, the query would select the department and sum of salaries, grouping by department. This groups the results by department and calculates the total salary for each department group.
The document discusses various SQL commands used for managing databases and querying data. It covers commands for creating and deleting databases and tables, inserting, updating, and deleting records, modifying table structures, grouping and filtering query results using aggregate functions and conditions, and ordering query results. Key SQL commands covered include CREATE, DROP, INSERT, UPDATE, DELETE, ALTER, SELECT, GROUP BY, HAVING, and ORDER BY.
1. The document discusses various SQL commands for creating, manipulating, and querying database tables. It covers commands like CREATE TABLE, INSERT, SELECT, UPDATE, DELETE, ALTER TABLE, COMMENT, and more.
2. Mathematical functions like COUNT, MAX, MIN, ROUND, TRUNC are described along with logical and comparison operators.
3. The document provides examples of using operators, functions, joins and grouping with detailed explanations.
Introduction to Oracle Functions--(SQL)--Abhishek Sharmaअभिषेक शर्मा
Functions make query results easier to understand and manipulate data values. There are two categories of functions: single row/scalar functions that return one value per row, and group/aggregate functions that operate on sets of values to return a single result. The GROUP BY clause groups rows based on columns and is used with aggregate functions to return summary results for each group.
The document discusses various aggregate functions used in SQL such as SUM, COUNT, AVG, MIN, and MAX. It provides examples of how to use these functions to retrieve aggregated data from tables, including the use of GROUP BY and HAVING clauses. Aggregate functions summarize data over multiple rows, returning a single value. COUNT(*) counts all rows while other functions like COUNT ignore NULL values.
Functions in Oracle can be used to manipulate data values and are categorized as single-row/scalar functions and group/aggregate functions. Single-row functions operate on each row and return one value per row, while group functions operate on sets of values to return one result. The GROUP BY clause is used to group or categorize data and can be used with aggregate functions to return summary results for each group.
The document discusses aggregate functions in SQL such as SUM, AVG, COUNT, MAX, MIN. It provides examples of using these functions to calculate totals, averages, counts and find maximum and minimum values from columns in tables. It also covers the use of the GROUP BY clause to perform aggregate calculations on grouped data and the HAVING clause to filter groups.
Reporting aggregated data using the group functionsSyed Zaid Irshad
Group functions operate on sets of rows to provide aggregate results for each group. Common group functions include COUNT, SUM, AVG, MIN, and MAX. The GROUP BY clause is used to divide rows into groups and must include any non-aggregate columns in the SELECT. The HAVING clause restricts groups based on aggregate conditions.
This document discusses how to use group functions in SQL to aggregate data and summarize it. It covers the available group functions like COUNT, MAX, MIN, AVG, and SUM. It explains how to use the GROUP BY clause to group data and the HAVING clause to restrict groups. It provides examples of queries that use group functions with GROUP BY and HAVING to summarize data at the group level.
The document provides information on various SQL functions. It discusses functions for sorting query results, performing calculations on aggregate data, grouping data, and filtering groups. Date and string functions are also covered, along with numeric and mathematical functions. Common functions include ORDER BY for sorting, SUM, AVG, COUNT for aggregates, GROUP BY for grouping, and HAVING for filtering groups. NOW() and SYSDATE() are described as functions for returning the current date and time.
e computer notes - Aggregating data using group functionsecomputernotes
This document discusses how to aggregate data using group functions in SQL. It describes various group functions like AVG, COUNT, MAX, MIN, SUM, and how to use the GROUP BY clause to group data and the HAVING clause to filter groups. It provides examples of finding average salary by department, counting distinct departments, summing salaries by job and department, and nesting group functions.
This document discusses cube, rollup and materialized views in Oracle databases. It provides an overview of how cube and rollup extend the GROUP BY clause to automatically calculate subtotals and totals. It also discusses how materialized views can store the results of a query to improve performance for frequent or complex queries. The document includes examples demonstrating how to use cube, rollup, and materialized views.
Huffman codes are a technique for lossless data compression that assigns variable-length binary codes to characters, with more frequent characters having shorter codes. The algorithm builds a frequency table of characters then constructs a binary tree to determine optimal codes. Characters are assigned codes based on their path from the root, with left branches representing 0 and right 1. Both encoder and decoder use this tree to translate between binary codes and characters. The tree guarantees unique decoding and optimal compression.
SQLite only supports left outer joins. A left outer join returns all rows from the left table, along with matched rows from the right table. If there is no match, the right side will contain null values. The document demonstrates a left outer join between a COMPANY table and an ORDERS table to return name, amount, and date from orders matched to companies.
Single-row functions allow users to manipulate data within SQL queries. Common types include character, number, date, and conversion functions. Character functions modify strings, number functions perform calculations, date functions work with dates, and conversion functions change data types. Functions are useful for formatting output, performing calculations on individual rows, and conditional processing.
SQL is a programming language used to communicate with and manipulate databases. It allows users to retrieve, insert, update and delete data from databases. Common SQL statements include JOINs, which combine data from two or more tables based on a common column. Some types of JOINs are INNER JOIN, which returns rows with matches in both tables; LEFT JOIN, which returns all rows from the left table; and FULL JOIN, which returns rows that match in either table. JOINs are often used with SELECT statements to query multiple tables at once.
This document discusses different types of communication networks within an organization:
1. Internal communication occurs within the organization, such as between a teacher and student.
2. External communication links the organization to outside entities, like between heads of two organizations.
3. Vertical communication flows up and down the hierarchy, including downward communication from managers to subordinates and upward communication with feedback from subordinates to managers.
4. Horizontal communication occurs between peers of equal rank in an organization.
5. Diagonal communication combines vertical and horizontal flows across different levels and departments when coordination is needed.
This document discusses different types of communication networks within an organization:
1. Internal communication occurs within the organization, such as between a teacher and student.
2. External communication links the organization to outside entities, like between heads of two organizations.
3. Vertical communication flows up and down the hierarchy, including downward communication from managers to subordinates and upward communication with feedback from subordinates to managers.
4. Horizontal communication occurs between peers of equal rank in an organization.
5. Diagonal communication combines vertical and horizontal flows across different levels and departments in an organization.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
2. Objectives
• After completing this lesson, you should
be able to do the following:
– Identify the available group functions
– Describe the use of group functions
– Group data using the GROUP BY clause
– Include 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.
EMPEMP
““maximummaximum
salary insalary in
the EMP table”the EMP table”
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000
20 3000
20 2975
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
MAX(SAL)
---------
5000
5. Using Group Functions
SELECT [column,] group_function(column)
FROM table
[WHERE condition]
[GROUP BY column]
[ORDER BY column];
6. Using AVG and SUM Functions
AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)
-------- --------- --------- ---------
1400 1600 1250 5600
• You can use AVG and SUM for numeric data.
SQL> SELECT AVG(sal), MAX(sal),
2 MIN(sal), SUM(sal)
3 FROM emp
4 WHERE job LIKE 'SALES%';
7. Using MIN and MAX Functions
• You can use MIN and MAX for any
datatype.SQL> SELECT MIN(hiredate), MAX(hiredate)
2 FROM emp;
MIN(HIRED MAX(HIRED
--------- ---------
17-DEC-80 12-JAN-83
8. Using the COUNT Function
COUNT(*)
---------
6
SQL> SELECT COUNT(*)
2 FROM emp
3 WHERE deptno = 30;
• COUNT(*) returns the number of rows in a
table.
9. Using the COUNT Function
• COUNT(expr) returns the number of
nonnull rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;
COUNT(COMM)
-----------
4
10. Group Functions and Null
Values• Group functions ignore null values in the
column.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------
550
11. Using the NVL Function
with Group Functions
• The 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. Creating Groups of Data
EMPEMP
““averageaverage
salarysalary
in EMPin EMP
tabletable
for eachfor each
department”department”
2916.66672916.6667
21752175
1566.66671566.6667
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000
20 3000
20 2975
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
DEPTNO AVG(SAL)
------- ---------
10 2916.6667
20 2175
30 1566.6667
13. Creating Groups of Data:
GROUP BY Clause
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];
• 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 emp
3 GROUP BY deptno;
DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.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 emp
3 GROUP BY deptno;
AVG(SAL)
---------
2916.6667
2175
1566.6667
16. Grouping by More
Than One ColumnEMPEMP
““sum salaries insum salaries in
the EMP tablethe EMP table
for each job,for each job,
grouped bygrouped by
department”department”
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
10 PRESIDENT 5000
10 CLERK 1300
20 CLERK 800
20 CLERK 1100
20 ANALYST 3000
20 ANALYST 3000
20 MANAGER 2975
30 SALESMAN 1600
30 MANAGER 2850
30 SALESMAN 1250
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
JOB SUM(SAL)
--------- ---------
CLERK 1300
MANAGER 2450
PRESIDENT 5000
ANALYST 6000
CLERK 1900
MANAGER 2975
CLERK 950
MANAGER 2850
SALESMAN 5600
DEPTNO
--------
10
10
10
20
20
20
30
30
30
17. Using the GROUP BY Clause
on Multiple Columns
SQL> SELECT deptno, job, sum(sal)
2 FROM emp
3 GROUP BY deptno, job;
DEPTNO JOB SUM(SAL)
--------- --------- ---------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
...
9 rows selected.
18. Illegal Queries
Using Group Functions
• Any column or expression in the SELECT
list that is not an aggregate function must
be in the GROUP BY clause.
SQL> SELECT deptno, COUNT(ename)
2 FROM emp;
SQL> SELECT deptno, COUNT(ename)
2 FROM emp;
SELECT deptno, COUNT(ename)
*
ERROR at line 1:
ORA-00937: not a single-group group function
SELECT deptno, COUNT(ename)
*
ERROR at line 1:
ORA-00937: not a single-group group function
Column missing in the GROUP BY clause
Column missing in the GROUP BY clause
19. Illegal Queries
Using Group Functions
– You cannot use the WHERE clause to restrict groups.
– You use the HAVING clause to restrict groups.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 WHERE AVG(sal) > 2000
4 GROUP BY deptno;
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 WHERE AVG(sal) > 2000
4 GROUP BY deptno;
WHERE AVG(sal) > 2000
*
ERROR at line 3:
ORA-00934: group function is not allowed here
WHERE AVG(sal) > 2000
*
ERROR at line 3:
ORA-00934: group function is not allowed here
Cannot use the WHERE clause
Cannot use the WHERE clause
to restrict groups
to restrict groups
21. Excluding Group Results:
HAVING Clause
• Use the HAVING clause to restrict groups
• Rows are grouped.
• The group function is applied.
• Groups matching the HAVING clause are
displayed.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
22. Using the HAVING Clause
SQL> SELECT deptno, max(sal)
2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
23. Using the HAVING Clause
SQL> SELECT job, SUM(sal) PAYROLL
2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
24. Nesting Group Functions
SQL> SELECT max(avg(sal))
2 FROM emp
3 GROUP BY deptno;
MAX(AVG(SAL))
-------------
2916.6667
• Display the maximum average salary.
25. Summary
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
• Order of evaluation of the clauses:
– WHERE clause
– GROUP BY clause
– HAVING clause
26. Practice Overview
– Showing different queries that use group functions
– Grouping by rows to achieve more than one result
– Excluding groups by using the HAVING clause
Lesson Aim
This lesson further addresses functions. It focuses on obtaining summary information, such as averages, for groups of rows. It discusses how to group rows in a table into smaller sets and how to specify search criteria for groups of rows.
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.
Group Functions (continued)
Each of the functions accepts an argument. The following table identifies the options that you can use in the 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 datatypes for the arguments may be CHAR, VARCHAR2, NUMBER, or DATE where expr is listed.
All group functions except COUNT(*) ignore null values. To substitute a value for null values, use the NVL function.
The Oracle Server implicitly sorts the result set in ascending order when using a GROUP BY clause. To override this default ordering, DESC can be used in an ORDER BY clause.
Class Management Note
Stress the use of DISTINCT and group functions ignoring null values. ALL is the default and is very rarely specified.
Group Functions
You can use AVG, SUM, MIN, and MAX functions against columns that can store numeric data. The example on the slide displays the average, highest, lowest, and sum of monthly salaries for all salespeople.
Group Functions (continued)
You can use MAX and MIN functions for any datatype. The slide example displays the most junior and most senior employee.
The following example displays the employee name that is first and the employee name that is the last in an alphabetized list of all employees.
Note: AVG, SUM, VARIANCE, and STDDEV functions can be used only with numeric datatypes.
The COUNT Function
The COUNT function has two formats:
COUNT(*)
COUNT(expr)
COUNT(*) returns the number of rows in a table, 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 satisfies the condition in the WHERE clause.
In contrast, COUNT(expr) returns the number of nonnull rows in the column identified by expr.
The slide example displays the number of employees in department 30.
Class Management Note
Demo: l5count1.sql, l5count2.sql
Purpose: To illustrate using the COUNT(*) and COUNT(expr) functions.
The COUNT Function (continued)
The slide example displays the number of employees in department 30 who can earn a commission. Notice that the result gives the total number of rows to be four because two employees in department 30 cannot earn a commission and contain a null value in the COMM column.
Example
Display the number of departments in the EMP table.
Display the number of distinct departments in the EMP table.
Group Functions and Null Values
All group functions except COUNT (*) ignore null values in the column. In the slide example, 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 total commission being paid to all employees divided by the number of employees receiving commission (4).
Group Functions and Null Values (continued)
The NVL function forces group functions to include null values. In the slide example, 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 total commission being paid to all employees divided by the total number of employees in the company (14).
Groups of Data
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. This can be done by using the GROUP BY clause.
The GROUP BY Clause
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_expressionspecifies columns whose values determine the basis forgrouping 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 will receive an error message if you fail to include the column list.
Using a WHERE clause, you can preexclude rows before dividing them into groups.
You must include the columns in the GROUP BY clause.
You cannot use the 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.
The GROUP BY Clause (continued)
When using the GROUP BY clause, make sure that all columns in the SELECT list that are not in the group functions are included in the GROUP BY clause. The example on the slide displays the department number and the average salary for each department. Here is how this SELECT statement, containing a GROUP BY clause, is evaluated:
The SELECT clause specifies the columns to be retrieved:
Department number column in the EMP table
The average of all the salaries in the group you specified in the GROUP BY clause
The FROM clause specifies the tables that the database must access: the EMP table.
The WHERE clause specifies the rows to be retrieved. Since there is no WHERE clause, by default all rows are retrieved.
The GROUP BY clause specifies how the rows should be grouped. The rows are being grouped by department number, so the AVG function that is being applied to the salary column will calculate the average salary for each department.
The GROUP BY Clause (continued)
The GROUP BY column does not have to be in the SELECT clause. For example, the SELECT statement on the slide displays the average salaries for each department without displaying the respective department numbers. Without the department numbers, however, the results do not look meaningful.
You can use the group function in the ORDER BY clause.
Class Management Note
Demonstrate the query with and without the DEPTNO in the SELECT statement.
Groups Within Groups
Sometimes there is a need to see results for groups within groups. The slide shows a report that displays the total salary being paid to each job title, within each department.
The EMP table is grouped first by department number, and within that grouping, it is grouped by job title. For example, the two clerks in department 20 are grouped together and a single result (total salary) is produced for all salespeople within the group.
Class Management Note
Demo: l5order1.sql,l5order2.sql
Purpose: To illustrate ordering columns that are grouped by DEPTNO first and ordering columns that are grouped by JOB first.
Groups Within Groups (continued)
You can return summary results for groups and subgroups by listing more than one GROUP BY column. You can determine the default sort order of the results by the order of the columns in the GROUP BY clause. Here is how the SELECT statement on the slide, containing a GROUP BY clause, is evaluated:
The SELECT clause specifies the column to be retrieved:
Department number in the EMP table
Job title in the EMP table
The sum of all the salaries in the group that you specified in the
GROUP BY clause
The FROM clause specifies the tables that the database must access: the EMP table.
The GROUP BY clause specifies how you must group the rows:
First, the rows are grouped by department number.
Second, within the department number groups, the rows are grouped by job title.
So the SUM function is being applied to the salary column for all job titles within each department number group.
Illegal Queries Using Group Functions
Whenever you use a mixture of individual items (DEPTNO) and group functions (COUNT) in the same SELECT statement, you must include a GROUP BY clause that specifies the individual items (in this case, DEPTNO). If the GROUP BY clause is missing, then the error message “not a single-group group function” appears and an asterisk (*) points to the offending column. You can correct the error on the slide by adding the GROUP BY clause.
Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.
Class Management Note
Demo: l5error.sql
Purpose: To illustrate executing a SELECT statement with no GROUP BY clause.
Restricting Group Results
In the same way that you use the WHERE clause to restrict the rows that you select, you use the HAVING clause to restrict groups. To find the maximum salary of each department, but show only the departments that have a maximum salary of more than $2900, you need to do the following:
Find the average salary for each department by grouping by department number.
Restrict the groups to those departments with a maximum salary greater than $2900.
The HAVING Clause
You use the HAVING clause to specify which groups are to be displayed. Therefore, you further restrict the groups on the basis of aggregate information.
In the syntax:
group_conditionrestricts the groups of rows returned to those groups for which the specified condition is TRUE
The Oracle Server performs the following steps when you use the HAVING clause:
Rows are grouped.
The group function is applied to the group.
The groups that match the criteria in the HAVING clause are displayed.
The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the GROUP BY clause first because it is more logical. Groups are formed and group functions are calculated before the HAVING clause is applied to the groups in the SELECT list.
The HAVING Clause (continued)
The slide example displays department numbers and maximum salary for those departments whose maximum salary is greater than $2900.
You can use the GROUP BY clause without using a group function in the SELECT list.
If you restrict rows based on the result of a group function, you must have a GROUP BY clause as well as the HAVING clause.
The following example displays the department numbers and average salary for those departments whose maximum salary is greater than $2900:
The HAVING Clause (continued)
The slide example displays the job title and total monthly salary for each job title with a total payroll exceeding $5000. The example excludes salespeople and sorts the list by the total monthly salary.
Class Management Note
Demo: l5job1.sql, l5job2.sql
Purpose: To illustrate using a WHERE clause to restrict rows by JOB and using a HAVING clause to restrict groups by SUM(SAL).
Nesting Group Functions
Group functions can be nested to a depth of two. The slide example displays the maximum average salary.
Summary
Seven group functions are available in SQL:
AVG
COUNT
MAX
MIN
SUM
STDDEV
VARIANCE
You can create subgroups by using the GROUP BY clause. Groups can be excluded using the HAVING clause.
Place the HAVING and GROUP BY clauses after the WHERE clause in a statement. Place the ORDER BY clause last.
The Oracle Server evaluates the clauses in the following order:
If the statement contains a WHERE clause, the server establishes the candidate rows.
The server identifies the groups specified in the GROUP BY clause.
The HAVING clause further restricts result groups that do not meet the group criteria in the HAVING clause.
Practice Overview
At the end of this practice, you should be familiar with using group functions and selecting groups of data.
Paper-Based Questions
For questions 1–3, circle either True or False.
Note: Column aliases are used for the queries.
Class Management Note
Hint for Practice #7: Advise the students to think about the MGR column in EMP when determining the number of managers, rather than the JOB column.