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.
This document discusses enhancements to the SQL GROUP BY clause, including how to use the ROLLUP and CUBE operations to produce subtotals and cross-tabulation values, respectively. It also covers using the GROUPING function to identify rows from ROLLUP or CUBE, and using GROUPING SETS to define multiple groupings in a single query. Examples are provided for each technique.
This document discusses advanced subquery techniques in SQL, including:
1) Writing multiple-column subqueries that can perform pairwise or nonpairwise comparisons.
2) Using scalar subqueries that return a single value in more clauses and expressions.
3) Writing correlated subqueries that are executed once per row to filter or update related data.
4) Using the EXISTS operator to check for matching rows in a subquery results set.
5) Leveraging the WITH clause to reuse query blocks and improve performance of complex queries.
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.
The document discusses single-row functions in SQL. It describes that single-row functions manipulate or return one value per row based on arguments. Examples of different types of single-row functions are provided, including character, number, date, and general functions. Specific functions like UPPER, ROUND, SYSDATE, and NVL are described along with examples of how to use them in SQL queries. Nesting of functions is also covered.
Sql server ___________session_10(group by clause)Ehtisham Ali
The GROUP BY clause is used to organize rows into groups and can be used with clauses like WHERE, HAVING, and operators like ROLLUP and CUBE. GROUP BY works with WHERE to restrict rows before grouping, groups null values separately, and ALL includes groups that don't meet search conditions. ROLLUP generates subtotals and totals, while CUBE shows aggregates for all column value combinations including totals.
Mysql PRO provides an overview of MySQL basics, architecture, transactions, triggers, PL/SQL, and engines. The document discusses SELECT statements, joins, INSERT, UPDATE, DELETE, and transactions. It explains MySQL architecture including optimization, execution, and concurrency control using table locks and row locks. Transactions ensure atomicity and consistency by allowing statements to be treated as single units that either all succeed or fail as a whole.
This document discusses enhancements to the SQL GROUP BY clause, including how to use the ROLLUP and CUBE operations to produce subtotals and cross-tabulation values, respectively. It also covers using the GROUPING function to identify rows from ROLLUP or CUBE, and using GROUPING SETS to define multiple groupings in a single query. Examples are provided for each technique.
This document discusses advanced subquery techniques in SQL, including:
1) Writing multiple-column subqueries that can perform pairwise or nonpairwise comparisons.
2) Using scalar subqueries that return a single value in more clauses and expressions.
3) Writing correlated subqueries that are executed once per row to filter or update related data.
4) Using the EXISTS operator to check for matching rows in a subquery results set.
5) Leveraging the WITH clause to reuse query blocks and improve performance of complex queries.
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.
The document discusses single-row functions in SQL. It describes that single-row functions manipulate or return one value per row based on arguments. Examples of different types of single-row functions are provided, including character, number, date, and general functions. Specific functions like UPPER, ROUND, SYSDATE, and NVL are described along with examples of how to use them in SQL queries. Nesting of functions is also covered.
Sql server ___________session_10(group by clause)Ehtisham Ali
The GROUP BY clause is used to organize rows into groups and can be used with clauses like WHERE, HAVING, and operators like ROLLUP and CUBE. GROUP BY works with WHERE to restrict rows before grouping, groups null values separately, and ALL includes groups that don't meet search conditions. ROLLUP generates subtotals and totals, while CUBE shows aggregates for all column value combinations including totals.
Mysql PRO provides an overview of MySQL basics, architecture, transactions, triggers, PL/SQL, and engines. The document discusses SELECT statements, joins, INSERT, UPDATE, DELETE, and transactions. It explains MySQL architecture including optimization, execution, and concurrency control using table locks and row locks. Transactions ensure atomicity and consistency by allowing statements to be treated as single units that either all succeed or fail as a whole.
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.
This document discusses functions and the GROUP BY clause in Oracle. It covers single row functions like character, number, date functions and aggregate functions that operate on multiple rows. Examples are provided to demonstrate character functions like INITCAP, UPPER, SUBSTR and number functions like ROUND, TRUNC, MOD. Date functions like MONTH, YEAR and date arithmetic are also covered. Conversion, general functions like NVL, NVL2, NULLIF are explained. The syntax for aggregate functions like COUNT, MIN, MAX, AVG, SUM with the GROUP BY clause is demonstrated to group and filter results.
The apply() function in R can apply functions over margins of arrays or matrices. It avoids explicit loops and applies the given function to each row or column or both. Some key advantages of apply() include avoiding explicit loops, ability to apply various functions like mean, median etc, and ability to apply user-defined functions. Similarly, lapply() and sapply() apply a function over the lists or vectors but lapply() returns a list while sapply() simplifies the output if possible. Functions like tapply() and by() are useful when dealing with categorical variables to apply functions across categories. mapply() applies a function to multiple arguments and is useful for multivariate functions.
This document discusses how to produce readable output using substitution variables and formatting commands in SQL*Plus. It covers how to:
1. Use substitution variables to prompt for and store values for use in SQL statements.
2. Customize the SQL*Plus environment using SET commands and control column formatting with COLUMN.
3. Create script files to run formatted reports by adding SQL*Plus commands before and after SELECT statements.
This document discusses single-row SQL functions. It defines single-row functions as functions that manipulate or return data for each row independently. The document categorizes common single-row functions such as character, number, date and conversion functions. It provides examples of how to use functions like TO_CHAR, TRUNC, and NVL. Nested functions and conditional expressions using DECODE are also introduced.
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.
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.
To understand about Operator.
To learn about how many types of Operator.
To learn about Arithmetic Operator in C.
To use of Bitwise Operator in C.
To use of Relational Operator in C.
To learn about Logical Operator in C.
To learn about Assignment Operator in C.
To learn about Ternary Operator in C.
To learn about Unary & Binary Operator.
The document provides an overview of various Oracle tips and tricks, including CASE statements, joins, timestamps, renaming tables/columns, merge statements, subqueries, window functions, hierarchical queries, XML, grouping sets, rollups and cubes, indexes, temporary tables and more. Key features introduced in Oracle 9i such as the CASE statement, full outer joins, timestamps and the WITH clause are highlighted.
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.
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.
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 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.
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.
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.
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.
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.
The document discusses various commands used in database management systems like Oracle. It explains commands to create, alter, delete and modify database tables. Additional commands covered include inserting, updating, selecting and displaying data from tables. Examples are provided for each command syntax. The document also discusses creating tables from other tables and inserting records between tables using queries. Finally, multiple exercises are provided to apply the covered 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.
e computer notes - Enhancements to the group by clauseecomputernotes
This document discusses enhancements to the SQL GROUP BY clause, including the ROLLUP, CUBE, GROUPING, and GROUPING SETS functions. ROLLUP produces subtotals, CUBE produces cross-tabulation values, and GROUPING differentiates between stored NULL values and those created by ROLLUP/CUBE. GROUPING SETS allows defining multiple groupings in a single query for improved efficiency. Examples are provided to demonstrate the usage of each enhancement.
Oracle Week 2015 presentation (Presented on November 15, 2015)
Agenda:
Aggregative and advanced grouping options
Analytic functions, ranking and pagination
Hierarchical and recursive queries
Oracle 12c new rows pattern matching feature
XML and JSON handling with SQL
Regular Expressions
SQLcl – a new replacement tool for SQL*Plus from Oracle
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.
This document discusses functions and the GROUP BY clause in Oracle. It covers single row functions like character, number, date functions and aggregate functions that operate on multiple rows. Examples are provided to demonstrate character functions like INITCAP, UPPER, SUBSTR and number functions like ROUND, TRUNC, MOD. Date functions like MONTH, YEAR and date arithmetic are also covered. Conversion, general functions like NVL, NVL2, NULLIF are explained. The syntax for aggregate functions like COUNT, MIN, MAX, AVG, SUM with the GROUP BY clause is demonstrated to group and filter results.
The apply() function in R can apply functions over margins of arrays or matrices. It avoids explicit loops and applies the given function to each row or column or both. Some key advantages of apply() include avoiding explicit loops, ability to apply various functions like mean, median etc, and ability to apply user-defined functions. Similarly, lapply() and sapply() apply a function over the lists or vectors but lapply() returns a list while sapply() simplifies the output if possible. Functions like tapply() and by() are useful when dealing with categorical variables to apply functions across categories. mapply() applies a function to multiple arguments and is useful for multivariate functions.
This document discusses how to produce readable output using substitution variables and formatting commands in SQL*Plus. It covers how to:
1. Use substitution variables to prompt for and store values for use in SQL statements.
2. Customize the SQL*Plus environment using SET commands and control column formatting with COLUMN.
3. Create script files to run formatted reports by adding SQL*Plus commands before and after SELECT statements.
This document discusses single-row SQL functions. It defines single-row functions as functions that manipulate or return data for each row independently. The document categorizes common single-row functions such as character, number, date and conversion functions. It provides examples of how to use functions like TO_CHAR, TRUNC, and NVL. Nested functions and conditional expressions using DECODE are also introduced.
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.
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.
To understand about Operator.
To learn about how many types of Operator.
To learn about Arithmetic Operator in C.
To use of Bitwise Operator in C.
To use of Relational Operator in C.
To learn about Logical Operator in C.
To learn about Assignment Operator in C.
To learn about Ternary Operator in C.
To learn about Unary & Binary Operator.
The document provides an overview of various Oracle tips and tricks, including CASE statements, joins, timestamps, renaming tables/columns, merge statements, subqueries, window functions, hierarchical queries, XML, grouping sets, rollups and cubes, indexes, temporary tables and more. Key features introduced in Oracle 9i such as the CASE statement, full outer joins, timestamps and the WITH clause are highlighted.
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.
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.
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 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.
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.
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.
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.
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.
The document discusses various commands used in database management systems like Oracle. It explains commands to create, alter, delete and modify database tables. Additional commands covered include inserting, updating, selecting and displaying data from tables. Examples are provided for each command syntax. The document also discusses creating tables from other tables and inserting records between tables using queries. Finally, multiple exercises are provided to apply the covered 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.
e computer notes - Enhancements to the group by clauseecomputernotes
This document discusses enhancements to the SQL GROUP BY clause, including the ROLLUP, CUBE, GROUPING, and GROUPING SETS functions. ROLLUP produces subtotals, CUBE produces cross-tabulation values, and GROUPING differentiates between stored NULL values and those created by ROLLUP/CUBE. GROUPING SETS allows defining multiple groupings in a single query for improved efficiency. Examples are provided to demonstrate the usage of each enhancement.
Oracle Week 2015 presentation (Presented on November 15, 2015)
Agenda:
Aggregative and advanced grouping options
Analytic functions, ranking and pagination
Hierarchical and recursive queries
Oracle 12c new rows pattern matching feature
XML and JSON handling with SQL
Regular Expressions
SQLcl – a new replacement tool for SQL*Plus from Oracle
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 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.
Aggregate functions summarize data from multiple rows into a single value. They operate on a single column and return a single value. Common aggregate functions include SUM, AVG, MIN, MAX, and COUNT. SUM returns the sum of numeric column values. AVG returns the average of numeric column values. MIN and MAX return the minimum and maximum values in a column. COUNT returns the number of rows.
This document discusses group functions in SQL, which operate on groups of rows and return results. It covers common group functions like COUNT, AVG, SUM, MIN, MAX, STDDEV and VARIANCE. It explains how to use the GROUP BY clause to group data by columns and the HAVING clause to include or exclude grouped rows. Examples are provided for counting rows, getting averages, and filtering groups. Nested groups and the order of operations are also discussed.
This is a presentation from Oracle Week 2016 (Israel). This is a newer version from last year with new 12cR2 features and demo.
In the agenda:
Aggregative and advanced grouping options
Analytic functions, ranking and pagination
Hierarchical and recursive queries
Regular Expressions
Oracle 12c new rows pattern matching
XML and JSON handling with SQL
Oracle 12c (12.1 + 12.2) new features
SQL Developer Command Line tool
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
Even though DBAs and developers are writing SQL queries every day, it seems that advanced SQL techniques such as multidimension aggregation and analytic functions still remain relatively unknown. In this session, we will explore some of the common real-world usages for analytic function and understand how to take advantage of this great and useful tool. We will deep dive into ranking based on values and groups, understand aggregation of multiple dimensions without a group by, see how to do inter-row calculations, and much more.
This is the presentation slides which was presented in Kscope 17 on June 28, 2017.
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 discusses functions and the GROUP BY clause in Oracle. It covers single row functions like character, number, date functions and aggregate functions that operate on multiple rows. Examples are provided to demonstrate character functions like INITCAP, UPPER, LOWER, number functions like ROUND, TRUNC, MOD, date functions like SYSDATE, and aggregate functions like COUNT, MIN, MAX, AVG, SUM. The GROUP BY clause is used to divide the table into groups based on a column and requires including that column in the SELECT statement along with any aggregate functions.
Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
Session from ILOUG I presented in May, 2016
Even though DBAs and developers are writing SQL queries every day, it seems that advanced SQL techniques such as multi-dimension aggregation and analytic functions are still relatively remain unknown. In this session, we will explore some of the common real-world usages for analytic function, and understand how to take advantage of this great and useful tool. We will deep dive into ranking based on values and groups; understand aggregation of multiple dimensions without a group by; see how to do inter-row calculations, and much-much more…
Together we will see how we can unleash the power of analytics using Oracle 11g best practices and Oracle 12c new features.
Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
Session from BGOUG I presented in June, 2016
Even though DBAs and developers are writing SQL queries every day, it seems that advanced SQL techniques such as multi-dimension aggregation and analytic functions are still relatively remain unknown. In this session, we will explore some of the common real-world usages for analytic function, and understand how to take advantage of this great and useful tool. We will deep dive into ranking based on values and groups; understand aggregation of multiple dimensions without a group by; see how to do inter-row calculations, and much-much more…
Together we will see how we can unleash the power of analytics using Oracle 11g best practices and Oracle 12c new features.
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.
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.
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.
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.
The art of querying – newest and advanced SQL techniquesZohar Elkayam
Presentation from Oracle Week 2017.
Agenda:
Aggregative and advanced grouping options
Analytic functions, ranking and pagination
Hierarchical and recursive queries
Regular Expressions
Oracle 12c new rows pattern matching
XML and JSON handling with SQL
Oracle 12c (12.1 + 12.2) new features
SQL Developer Command Line tool (if time allows)
Oracle 18c
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
OOW2016: Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
This is the presentation I gave on the Oracle Open World 2016 - the topic was group functions and analytic functions.
We talked about reporting analytic functions, ranking and couple of Oracle 12c new features like top-n query syntax and pattern matching.
This presentation has the bonus slides which were not presented at the event itself, as promissed
The document discusses SQL commands for updating tables, deleting rows from tables, adding and modifying columns in tables, removing tables and views, and using aggregate functions and clauses. It provides syntax examples for the UPDATE, DELETE, ALTER TABLE, DROP TABLE, CREATE VIEW, DROP VIEW, and aggregate function/GROUP BY/HAVING clauses.
XML is a markup language that allows users to define their own tags and structure for documents. It separates content from formatting and is extensible, platform-independent, and human-readable. Well-formed XML documents follow syntax rules like having matching open and close tags and properly nested elements. Valid XML documents also comply with constraints defined in their associated DTD. Common XML components include elements, attributes, namespaces, comments, and CDATA sections.
This document provides an overview of XML (Extensible Markup Language) including:
- The basic structure and components of an XML document including elements, attributes, entities, and advanced components.
- An example well-commented XML document.
- The basic rules for creating a well-formed XML document including being case sensitive, requiring start and end tags, proper nesting, and more.
- Common errors in element naming and how to avoid them.
- How to walk through modifying an example XML document to add new elements and ensure it remains well-formed.
XML (Extensible Markup Language) allows users to define their own customized markup languages to structure data. It was created as a simplified version of SGML to make it usable on the web. XML is important because it removes constraints of HTML and allows for richer content than HTML alone. XML will enable easier exchange of data between businesses and applications.
XML is a markup language that allows users to define their own tags and structure for documents. It separates content from formatting and is extensible, platform-independent, and human-readable. Well-formed XML documents follow syntax rules like having matching open and close tags and properly nested elements. Valid XML documents also comply with constraints defined in their associated DTD. Common XML components include elements, attributes, namespaces, comments, and CDATA sections.
This document provides an overview of XML (Extensible Markup Language) including:
- The basic structure and components of an XML document including elements, attributes, entities, and advanced components.
- An example well-commented XML document.
- The basic rules for creating a well-formed XML document including being case sensitive, requiring start and end tags, proper nesting, and more.
- Common errors in element naming and how to avoid them.
- How to add new elements and attributes to an example XML document to ensure it remains well-formed.
XML stands for Extensible Markup Language and is used to mark up data so it can be processed by computers, whereas HTML is used to mark up text to be displayed for users. Both XML and HTML use elements enclosed in tags, attributes, and entities, but XML only describes content while HTML describes both structure and appearance. XML allows users to define their own tags, and is strictly structured, making it suitable for data processing by computers.
This document provides an overview of XML, including its basic structure and components. XML documents use elements to structure and tag content. Elements must be properly nested within a single root element and can have attributes. The relationships between these elements form a tree structure. XML documents also support comments, processing instructions, and character encoding. CSS and XSLT can be used to display and transform XML for web users. While databases are better for structured data, XML is well suited for loosely structured or large records.
The document provides an introduction to shell scripting basics in UNIX/Linux. It discusses what a shell and shell script are, introduces the popular bash shell, and covers running commands, variables, logic, and other shell scripting concepts. The key points covered include:
- A shell is a program that takes commands and runs other programs. Popular shells include bash, csh, tcsh, and ksh.
- A shell script is a text file containing shell commands that is executable. Creating and running a simple "Hello world" script is demonstrated.
- Running commands, pipes, redirection, variables, logic, and flow control like if/else, for loops are explained.
- Useful bash
This document provides an introduction and overview of the Unix operating system. It covers topics such as getting help, the file system, the shell, network security, email clients, text editors, input/output redirection, printing, process management, and the X window system. The document is intended to help new Unix users understand basic Unix concepts and commands.
Linux is an open source operating system created by Linus Torvalds in 1991. It uses a Linux kernel and includes many common Unix tools. Linux is free to use and modify due to its open source licensing. It runs on many hardware platforms and is growing in popularity for servers, desktops, and embedded systems due to its low cost, stability, and security. Users can download Linux from distributions like Red Hat which package the Linux kernel with additional software and support.
After completing this section, students should be able to log into the Linux system, understand and manipulate the UNIX file system, describe the role of the shell, use basic file commands like cd, ls, cp, and rm, use standard input/output and piping, and understand the UNIX philosophy. The document provides an introduction to UNIX operating systems, shells, file systems, basic commands, and input/output redirection.
This document provides an overview of the C programming language, including its history, characteristics, and syntax. C was developed in the 1970s alongside Unix and became widely used for system programming. It allows for close interaction with the operating system and hardware. The document walks through a simple "Hello World" program to demonstrate C's syntax, including preprocessing, compilation, linking, and execution. It also provides a more complex guessing game example to illustrate additional C language features like variables, operators, conditionals, and loops.
This document provides an introduction to the C programming language. It discusses key concepts like functions, variables, data types, memory, scopes, expressions, operators, control flow with if/else statements and loops. It also explains how passing arguments by value means functions cannot directly modify their parameters, but passing addresses allows modifying variables in the calling scope. Overall it serves as a helpful primer on basic C syntax and programming concepts for newcomers to the language.
This document provides an overview of introductory concepts in C programming, including simple programs to print text and perform arithmetic. It covers basic syntax like comments, functions, variables, data types, operators, input/output, and conditional statements. Memory concepts are introduced, as well as the preprocessor, standard libraries, and control flow structures like if/else. Examples are provided to demonstrate printing text, taking user input, performing calculations, and making decisions based on relational comparisons.
This document provides an introduction to C programming over 13 pages. It covers the purpose and schedule of the lectures, differences between C and Java, C program structure, keywords, variables, data types, and more. The main points are that the lectures will provide a crash course in C with an emphasis on differences from Java, cover practical examples and topics related to C programming, and include history, language overview, pointers, memory management, compiling and debugging.
This document provides an introduction to programming in C. It begins by discussing computers, hardware, software, data, and information processing. It then discusses what programming is and how to approach solving problems through programming. The document outlines the major components of a C program and provides a first example program. It also covers key C programming concepts like variables, data types, expressions, control flow, functions, pointers, arrays, strings, structures, files and memory allocation. The document is intended to introduce readers to programming in C from a high level.
The document provides an overview of the C programming language. It begins with a brief history of C and how it evolved from the B programming language to support UNIX. It describes C as a systems programming language that is close to hardware but with higher-level constructs than assembly. The rest of the document outlines key C language concepts like data types, variables, operators, functions, and control structures. It provides examples of how to use basic programming elements like if/else statements and switch statements.
This document contains repeated text about printing or viewing notes pages for a preface rather than slides. It provides instructions to print or view notes pages for a preface section eight separate times without any other notable information.
This document provides an overview and objectives for a course on Oracle database administration. It covers topics such as controlling user access, managing schema objects, manipulating large data sets, generating reports, managing data in different time zones, retrieving data using subqueries, hierarchical retrieval, and regular expression support. Each chapter provides learning objectives and exercises for students to reinforce the concepts covered.
Regular expressions can be used in SQL to search, match, and replace strings. Key regular expression functions include REGEXP_INSTR, REGEXP_SUBSTR, and REGEXP_REPLACE. Meta characters like *, +, and [] are used to define patterns to match. For example, 'a+' would match one or more occurrences of 'a' in a string.
Economic Risk Factor Update: June 2024 [SlideShare]Commonwealth
May’s reports showed signs of continued economic growth, said Sam Millette, director, fixed income, in his latest Economic Risk Factor Update.
For more market updates, subscribe to The Independent Market Observer at https://blog.commonwealth.com/independent-market-observer.
"Does Foreign Direct Investment Negatively Affect Preservation of Culture in the Global South? Case Studies in Thailand and Cambodia."
Do elements of globalization, such as Foreign Direct Investment (FDI), negatively affect the ability of countries in the Global South to preserve their culture? This research aims to answer this question by employing a cross-sectional comparative case study analysis utilizing methods of difference. Thailand and Cambodia are compared as they are in the same region and have a similar culture. The metric of difference between Thailand and Cambodia is their ability to preserve their culture. This ability is operationalized by their respective attitudes towards FDI; Thailand imposes stringent regulations and limitations on FDI while Cambodia does not hesitate to accept most FDI and imposes fewer limitations. The evidence from this study suggests that FDI from globally influential countries with high gross domestic products (GDPs) (e.g. China, U.S.) challenges the ability of countries with lower GDPs (e.g. Cambodia) to protect their culture. Furthermore, the ability, or lack thereof, of the receiving countries to protect their culture is amplified by the existence and implementation of restrictive FDI policies imposed by their governments.
My study abroad in Bali, Indonesia, inspired this research topic as I noticed how globalization is changing the culture of its people. I learned their language and way of life which helped me understand the beauty and importance of cultural preservation. I believe we could all benefit from learning new perspectives as they could help us ideate solutions to contemporary issues and empathize with others.
Dr. Alyce Su Cover Story - China's Investment Leadermsthrill
In World Expo 2010 Shanghai – the most visited Expo in the World History
https://www.britannica.com/event/Expo-Shanghai-2010
China’s official organizer of the Expo, CCPIT (China Council for the Promotion of International Trade https://en.ccpit.org/) has chosen Dr. Alyce Su as the Cover Person with Cover Story, in the Expo’s official magazine distributed throughout the Expo, showcasing China’s New Generation of Leaders to the World.
Optimizing Net Interest Margin (NIM) in the Financial Sector (With Examples).pdfshruti1menon2
NIM is calculated as the difference between interest income earned and interest expenses paid, divided by interest-earning assets.
Importance: NIM serves as a critical measure of a financial institution's profitability and operational efficiency. It reflects how effectively the institution is utilizing its interest-earning assets to generate income while managing interest costs.
Fabular Frames and the Four Ratio ProblemMajid Iqbal
Digital, interactive art showing the struggle of a society in providing for its present population while also saving planetary resources for future generations. Spread across several frames, the art is actually the rendering of real and speculative data. The stereographic projections change shape in response to prompts and provocations. Visitors interact with the model through speculative statements about how to increase savings across communities, regions, ecosystems and environments. Their fabulations combined with random noise, i.e. factors beyond control, have a dramatic effect on the societal transition. Things get better. Things get worse. The aim is to give visitors a new grasp and feel of the ongoing struggles in democracies around the world.
Stunning art in the small multiples format brings out the spatiotemporal nature of societal transitions, against backdrop issues such as energy, housing, waste, farmland and forest. In each frame we see hopeful and frightful interplays between spending and saving. Problems emerge when one of the two parts of the existential anaglyph rapidly shrinks like Arctic ice, as factors cross thresholds. Ecological wealth and intergenerational equity areFour at stake. Not enough spending could mean economic stress, social unrest and political conflict. Not enough saving and there will be climate breakdown and ‘bankruptcy’. So where does speculative design start and the gambling and betting end? Behind each fabular frame is a four ratio problem. Each ratio reflects the level of sacrifice and self-restraint a society is willing to accept, against promises of prosperity and freedom. Some values seem to stabilise a frame while others cause collapse. Get the ratios right and we can have it all. Get them wrong and things get more desperate.
Madhya Pradesh, the "Heart of India," boasts a rich tapestry of culture and heritage, from ancient dynasties to modern developments. Explore its land records, historical landmarks, and vibrant traditions. From agricultural expanses to urban growth, Madhya Pradesh offers a unique blend of the ancient and modern.
[4:55 p.m.] Bryan Oates
OJPs are becoming a critical resource for policy-makers and researchers who study the labour market. LMIC continues to work with Vicinity Jobs’ data on OJPs, which can be explored in our Canadian Job Trends Dashboard. Valuable insights have been gained through our analysis of OJP data, including LMIC research lead
Suzanne Spiteri’s recent report on improving the quality and accessibility of job postings to reduce employment barriers for neurodivergent people.
Decoding job postings: Improving accessibility for neurodivergent job seekers
Improving the quality and accessibility of job postings is one way to reduce employment barriers for neurodivergent people.
Discover the Future of Dogecoin with Our Comprehensive Guidance36 Crypto
Learn in-depth about Dogecoin's trajectory and stay informed with 36crypto's essential and up-to-date information about the crypto space.
Our presentation delves into Dogecoin's potential future, exploring whether it's destined to skyrocket to the moon or face a downward spiral. In addition, it highlights invaluable insights. Don't miss out on this opportunity to enhance your crypto understanding!
https://36crypto.com/the-future-of-dogecoin-how-high-can-this-cryptocurrency-reach/
KYC Compliance: A Cornerstone of Global Crypto Regulatory FrameworksAny kyc Account
This presentation explores the pivotal role of KYC compliance in shaping and enforcing global regulations within the dynamic landscape of cryptocurrencies. Dive into the intricate connection between KYC practices and the evolving legal frameworks governing the crypto industry.
Vicinity Jobs’ data includes more than three million 2023 OJPs and thousands of skills. Most skills appear in less than 0.02% of job postings, so most postings rely on a small subset of commonly used terms, like teamwork.
Laura Adkins-Hackett, Economist, LMIC, and Sukriti Trehan, Data Scientist, LMIC, presented their research exploring trends in the skills listed in OJPs to develop a deeper understanding of in-demand skills. This research project uses pointwise mutual information and other methods to extract more information about common skills from the relationships between skills, occupations and regions.
8. ROLLUP Operator: Example 3 1 2 SELECT department_id, job_id, SUM(salary) FROM employees WHERE department_id < 60 GROUP BY ROLLUP(department_id, job_id);
9.
10. CUBE Operator: Example SELECT department_id, job_id, SUM(salary) FROM employees WHERE department_id < 60 GROUP BY CUBE (department_id, job_id) ; 1 2 3 4
11.
12. GROUPING Function: Example SELECT department_id DEPTID, job_id JOB, SUM(salary), GROUPING(department_id) GRP_DEPT, GROUPING(job_id) GRP_JOB FROM employees WHERE department_id < 50 GROUP BY ROLLUP(department_id, job_id); 1 2 3
19. Composite Columns: Example SELECT department_id, job_id, manager_id, SUM(salary) FROM employees GROUP BY ROLLUP( department_id,(job_id, manager_id)); … 2 1 3 4
20.
21.
22. Concatenated Groupings: Example … … … SELECT department_id, job_id, manager_id, SUM(salary) FROM employees GROUP BY department_id, ROLLUP(job_id), CUBE(manager_id); 1 2 3 4 5
23.
24.
25.
26.
27.
28.
29.
30.
Editor's Notes
Oracle Database 10 g : SQL Fundamentals II 4- Objectives In this lesson you learn how to: Group data to obtain the following: Subtotal values by using the ROLLUP operator Cross-tabulation values by using the CUBE operator Use the GROUPING function to identify the level of aggregation in the result set produced by a ROLLUP or CUBE operator Use GROUPING SETS to produce a single result set that is equivalent to a UNION ALL approach
Oracle Database 10 g : SQL Fundamentals II 4- Group Functions You can use the GROUP BY clause to divide the rows in a table into groups. You can then use group functions to return summary information for each group. Group functions can appear in select lists and in ORDER BY and HAVING clauses. The Oracle server applies the group functions to each group of rows and returns a single result row for each group. Types of group functions: Each of the group functions AVG , SUM , MAX , MIN , COUNT , STDDEV , and VARIANCE accept one argument. The functions AVG , SUM , STDDEV , and VARIANCE operate only on numeric values. MAX and MIN can operate on numeric, character, or date data values. COUNT returns the number of non-null rows for the given expression. The example on the slide calculates the average salary, standard deviation on the salary, number of employees earning a commission, and the maximum hire date for those employees whose JOB_ID begins with SA. Guidelines for Using Group Functions The data types for the arguments can be CHAR , VARCHAR2 , NUMBER , or DATE . All group functions except COUNT(*) ignore null values. To substitute a value for null values, use the NVL function. COUNT returns either a number or zero. The Oracle server implicitly sorts the result set in ascending order of the grouping columns specified, when you use a GROUP BY clause. To override this default ordering, you can use DESC in an ORDER BY clause.
Oracle Database 10 g : SQL Fundamentals II 4- Review of GROUP BY Clause The example illustrated on the slide is evaluated by the Oracle server as follows: The SELECT clause specifies that the following columns are to be retrieved: Department ID and job ID columns from the EMPLOYEES table The sum of all the salaries and the number of employees in each group that you have specified in the GROUP BY clause The GROUP BY clause specifies how the rows should be grouped in the table. The total salary and the number of employees are calculated for each job ID within each department. The rows are grouped by department ID and then grouped by job within each department.
Oracle Database 10 g : SQL Fundamentals II 4- The HAVING Clause Groups are formed and group functions are calculated before the HAVING clause is applied to the groups. 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. The Oracle server performs the following steps when you use the HAVING clause: 1. Groups rows 2. Applies the group functions to the groups and displays the groups that match the criteria in the HAVING clause
Oracle Database 10 g : SQL Fundamentals II 4- GROUP BY with the ROLLUP and CUBE Operators You specify ROLLUP and CUBE operators in the GROUP BY clause of a query. ROLLUP grouping produces a result set containing the regular grouped rows and subtotal rows. The CUBE operation in the GROUP BY clause groups the selected rows based on the values of all possible combinations of expressions in the specification and returns a single row of summary information for each group. You can use the CUBE operator to produce cross-tabulation rows. Note: When working with ROLLUP and CUBE , make sure that the columns following the GROUP BY clause have meaningful, real-life relationships with each other; otherwise the operators return irrelevant information.
Oracle Database 10 g : SQL Fundamentals II 4- The ROLLUP Operator The ROLLUP operator delivers aggregates and superaggregates for expressions within a GROUP BY statement. The ROLLUP operator can be used by report writers to extract statistics and summary information from result sets. The cumulative aggregates can be used in reports, charts, and graphs. The ROLLUP operator creates groupings by moving in one direction, from right to left, along the list of columns specified in the GROUP BY clause. It then applies the aggregate function to these groupings. Note To produce subtotals in n dimensions (that is, n columns in the GROUP BY clause) without a ROLLUP operator, n +1 SELECT statements must be linked with UNION ALL . This makes the query execution inefficient, because each of the SELECT statements causes table access. The ROLLUP operator gathers its results with just one table access. The ROLLUP operator is useful when there are many columns involved in producing the subtotals. Subtotals and totals are produced with ROLLUP . CUBE produces totals as well but effectively rolls up in each possible direction, producing cross-tabular data.
Oracle Database 10 g : SQL Fundamentals II 4- Example of a ROLLUP Operator In the example on the slide: Total salaries for every job ID within a department for those departments whose department ID is less than 60 are displayed by the GROUP BY clause. The ROLLUP operator displays: Total salary for each department whose department ID is less than 60 Total salary for all departments whose department ID is less than 60, irrespective of the job IDs In this example, 1 indicates a group totaled by both DEPARTMENT_ID and JOB_ID , 2 indicates a group totaled only by DEPARTMENT_ID , and 3 indicates the grand total. The ROLLUP operator creates subtotals that roll up from the most detailed level to a grand total, following the grouping list specified in the GROUP BY clause. First, it calculates the standard aggregate values for the groups specified in the GROUP BY clause (in the example, the sum of salaries grouped on each job within a department). Then it creates progressively higher-level subtotals, moving from right to left through the list of grouping columns. (In the example, the sum of salaries for each department is calculated, followed by the sum of salaries for all departments.) Given n expressions in the ROLLUP operator of the GROUP BY clause, the operation results in n + 1 (in this case 2 + 1 = 3) groupings. Rows based on the values of the first n expressions are called rows or regular rows and the others are called superaggregate rows.
Oracle Database 10 g : SQL Fundamentals II 4- The CUBE Operator The CUBE operator is an additional switch in the GROUP BY clause in a SELECT statement. The CUBE operator can be applied to all aggregate functions, including AVG , SUM , MAX , MIN , and COUNT . It is used to produce result sets that are typically used for cross-tabular reports. Whereas ROLLUP produces only a fraction of possible subtotal combinations, CUBE produces subtotals for all possible combinations of groupings specified in the GROUP BY clause, and a grand total. The CUBE operator is used with an aggregate function to generate additional rows in a result set. Columns included in the GROUP BY clause are cross-referenced to produce a superset of groups. The aggregate function specified in the select list is applied to these groups to produce summary values for the additional superaggregate rows. The number of extra groups in the result set is determined by the number of columns included in the GROUP BY clause. In fact, every possible combination of the columns or expressions in the GROUP BY clause is used to produce superaggregates. If you have n columns or expressions in the GROUP BY clause, there will be 2 n possible superaggregate combinations. Mathematically, these combinations form an n -dimensional cube, which is how the operator got its name. By using application or programming tools, these superaggregate values can then be fed into charts and graphs that convey results and relationships visually and effectively.
Oracle Database 10 g : SQL Fundamentals II 4- Example of a CUBE Operator The output of the SELECT statement in the example can be interpreted as follows: The total salary for every job within a department (for those departments whose department ID is less than 60) is displayed by the GROUP BY clause. The total salary for those departments whose department ID is less than 60. The total salary for every job irrespective of the department. Total salary for those departments whose department ID is less than 60, irrespective of the job titles. In this example, 1 indicates the grand total. 2 indicates the rows totaled by JOB_ID alone. 3 indicates some of the rows totaled by DEPARTMENT_ID and JOB_ID . 4 indicates some of the rows totaled by DEPARTMENT_ID alone. The CUBE operator has also performed the ROLLUP operation to display the subtotals for those departments whose department ID is less than 60 and the total salary for those departments whose department ID is less than 60, irrespective of the job titles. Additionally, the CUBE operator displays the total salary for every job irrespective of the department. Note: Similar to the ROLLUP operator, producing subtotals in n dimensions (that is, n columns in the GROUP BY clause) without a CUBE operator requires that 2 n SELECT statements be linked with UNION ALL . Thus, a report with three dimensions requires 2 3 = 8 SELECT statements to be linked with UNION ALL .
Oracle Database 10 g : SQL Fundamentals II 4- The GROUPING Function The GROUPING function can be used with either the CUBE or ROLLUP operator to help you understand how a summary value has been obtained. The GROUPING function uses a single column as its argument. The expr in the GROUPING function must match one of the expressions in the GROUP BY clause. The function returns a value of 0 or 1. The values returned by the GROUPING function are useful to: Determine the level of aggregation of a given subtotal; that is, the group or groups on which the subtotal is based Identify whether a NULL value in the expression column of a row of the result set indicates: A NULL value from the base table (stored NULL value) A NULL value created by ROLLUP or CUBE (as a result of a group function on that expression) A value of 0 returned by the GROUPING function based on an expression indicates one of the following: The expression has been used to calculate the aggregate value. The NULL value in the expression column is a stored NULL value. A value of 1 returned by the GROUPING function based on an expression indicates one of the following: The expression has not been used to calculate the aggregate value. The NULL value in the expression column is created by ROLLUP or CUBE as a result of grouping.
Oracle Database 10 g : SQL Fundamentals II 4- Example of a GROUPING Function In the example on the slide, consider the summary value 4400 in the first row (labeled 1). This summary value is the total salary for the job ID of AD_ASST within department 10. To calculate this summary value, both the DEPARTMENT_ID and JOB_ID columns have been taken into account. Thus, a value of 0 is returned for both the GROUPING(department_id) and GROUPING(job_id) expressions. Consider the summary value 4400 in the second row (labeled 2). This value is the total salary for department 10 and has been calculated by taking into account the DEPARTMENT_ID column; thus, a value of 0 has been returned by GROUPING(department_id) . Because the JOB_ID column has not been taken into account to calculate this value, a value of 1 has been returned for GROUPING(job_id) . You can observe similar output in the fifth row. In the last row, consider the summary value 54800 (labeled 3). This is the total salary for those departments whose department ID is less than 50 and all job titles. To calculate this summary value, neither of the DEPARTMENT_ID and JOB_ID columns have been taken into account. Thus a value of 1 is returned for both the GROUPING(department_id) and GROUPING(job_id) expressions.
Oracle Database 10 g : SQL Fundamentals II 4- GROUPING SETS GROUPING SETS is a further extension of the GROUP BY clause that you can use to specify multiple groupings of data. Doing so facilitates efficient aggregation and, therefore, facilitates analysis of data across multiple dimensions. A single SELECT statement can now be written using GROUPING SETS to specify various groupings (which can also include ROLLUP or CUBE operators), rather than multiple SELECT statements combined by UNION ALL operators. For example: SELECT department_id, job_id, manager_id, AVG(salary) FROM employees GROUP BY GROUPING SETS ((department_id, job_id, manager_id), (department_id, manager_id),(job_id, manager_id)); This statement calculates aggregates over three groupings: (department_id, job_id, manager_id), (department_id, manager_id)and (job_id, manager_id) Without this feature, multiple queries combined together with UNION ALL are required to obtain the output of the preceding SELECT statement. A multiquery approach is inefficient, because it requires multiple scans of the same data.
Oracle Database 10 g : SQL Fundamentals II 4- GROUPING SETS (continued) Compare the previous example with the following alternative: SELECT department_id, job_id, manager_id, AVG(salary) FROM employees GROUP BY CUBE(department_id, job_id, manager_id); This statement computes all the 8 (2 *2 *2) groupings, though only the groups (department_id, job_id, manager_id) , (department_id, manager_id) , and (job_id, manager_id) are of interest to you. Another alternative is the following statement: SELECT department_id, job_id, manager_id, AVG(salary) FROM employees GROUP BY department_id, job_id, manager_id UNION ALL SELECT department_id, NULL, manager_id, AVG(salary) FROM employees GROUP BY department_id, manager_id UNION ALL SELECT NULL, job_id, manager_id, AVG(salary) FROM employees GROUP BY job_id, manager_id; This statement requires three scans of the base table, which makes it inefficient. CUBE and ROLLUP can be thought of as grouping sets with very specific semantics. The following equivalencies show this fact: GROUPING SETS ((a, b, c), (a, b),(a), ()) ROLLUP(a, b,c) is equivalent to GROUPING SETS ((a, b, c), (a, b), (a, c), (b, c), (a), (b), (c), ()) CUBE(a, b, c) is equivalent to
Oracle Database 10 g : SQL Fundamentals II 4- GROUPING SETS : Example The query on the slide calculates aggregates over two groupings. The table is divided into the following groups: Job ID, Manager ID Department ID, Job ID The average salaries for each of these groups are calculated. The result set displays the average salary for each of the two groups. In the output, the group marked as 1 can be interpreted as: The average salary of all employees with the job ID AD_VP under manager 100 is 17000. The average salary of all employees with the job ID AC_MGR under manager 101 is 12000, and so on. The group marked as 2 in the output is interpreted as: The average salary of all employees with the job ID FI_MGR in department 100 is 12000. The average salary of all employees with the job ID FI_ACCOUNT in department 100 is 7920, and so on.
Oracle Database 10 g : SQL Fundamentals II 4- GROUPING SETS : Example (continued) The example on the slide can also be written as: SELECT department_id, job_id, NULL as manager_id, AVG(salary) as AVGSAL FROM employees GROUP BY department_id, job_id UNION ALL SELECT NULL, job_id, manager_id, avg(salary) as AVGSAL FROM employees GROUP BY job_id, manager_id; In the absence of an optimizer that looks across query blocks to generate the execution plan, the preceding query would need two scans of the base table, EMPLOYEES . This could be very inefficient. Therefore, the usage of the GROUPING SETS statement is recommended.
Oracle Database 10 g : SQL Fundamentals II 4- Composite Columns A composite column is a collection of columns that are treated as a unit during the computation of groupings. You specify the columns in parentheses as in the following statement: ROLLUP (a, (b, c), d) Here, (b,c) forms a composite column and is treated as a unit. In general, composite columns are useful in ROLLUP , CUBE , and GROUPING SETS . For example, in CUBE or ROLLUP , composite columns would require skipping aggregation across certain levels. That is, GROUP BY ROLLUP(a, (b, c)) is equivalent to GROUP BY a, b, c UNION ALL GROUP BY a UNION ALL GROUP BY () Here, (b, c) is treated as a unit and ROLLUP is not applied across (b, c) . It is as if you have an alias, for example z , for (b, c) , and the GROUP BY expression reduces to GROUP BY ROLLUP(a, z) . Note: GROUP BY( ) is typically a SELECT statement with NULL values for the columns a and b and only the aggregate function. This is generally used for generating grand totals. SELECT NULL, NULL, aggregate_col FROM <table_name> GROUP BY ( );
Oracle Database 10 g : SQL Fundamentals II 4- Composite Columns (continued) Compare this with the normal ROLLUP as in: GROUP BY ROLLUP(a, b, c) which would be GROUP BY a, b, c UNION ALL GROUP BY a, b UNION ALL GROUP BY a UNION ALL GROUP BY () Similarly, GROUP BY CUBE((a, b), c) would be equivalent to GROUP BY a, b, c UNION ALL GROUP BY a, b UNION ALL GROUP BY c UNION ALL GROUP By () The following table shows grouping sets specification and the equivalent GROUP BY specification. GROUP BY a UNION ALL GROUP BY b UNION ALL GROUP BY () GROUP BY GROUPING SETS(a, (b), ()) GROUP BY a UNION ALL GROUP BY ROLLUP(b, c) GROUP BY GROUPING SETS (a,ROLLUP(b, c)) (The GROUPING SETS expression has a composite column.) GROUP BY a, b, c GROUP BY GROUPING SETS((a, b, c)) GROUP BY a UNION ALL GROUP BY b UNION ALL GROUP BY b, c GROUP BY GROUPING SETS(a, b,(b, c)) (The GROUPING SETS expression has a composite column.) GROUP BY a UNION ALL GROUP BY b UNION ALL GROUP BY c GROUP BY GROUPING SETS(a, b, c) Equivalent GROUP BY Statements GROUPING SETS Statements
Oracle Database 10 g : SQL Fundamentals II 4- Composite Columns: Example Consider the example: SELECT department_id, job_id,manager_id, SUM(salary) FROM employees GROUP BY ROLLUP( department_id,job_id, manager_id); This query results in the Oracle server computing the following groupings: 1. (job_id, manager_id) 2. (department_id, job_id, manager_id) 3. (department_id) 4. Grand total If you are only interested in specific groups, you cannot limit the calculation to those groupings without using composite columns. With composite columns, this is possible by treating JOB_ID and MANAGER_ID columns as a single unit while rolling up. Columns enclosed in parentheses are treated as a unit while computing ROLLUP and CUBE . This is illustrated in the example on the slide. By enclosing the JOB_ID and MANAGER_ID columns in parentheses, you indicate to the Oracle server to treat JOB_ID and MANAGER_ID as a single unit, that is a composite column.
Oracle Database 10 g : SQL Fundamentals II 4- Composite Columns: Example (continued) The example on the slide computes the following groupings: (department_id, job_id, manager_id) (department_id) ( ) The example on the slide displays the following: Total salary for every job , and manager (labeled 1) Total salary for every department, job , and manager (labeled 2) Total salary for every department (labeled 3) Grand total (labeled 4) The example on the slide can also be written as: SELECT department_id, job_id, manager_id, SUM(salary) FROM employees GROUP BY department_id,job_id, manager_id UNION ALL SELECT department_id, TO_CHAR(NULL),TO_NUMBER(NULL), SUM(salary) FROM employees GROUP BY department_id UNION ALL SELECT TO_NUMBER(NULL), TO_CHAR(NULL),TO_NUMBER(NULL), SUM(salary) FROM employees GROUP BY (); In the absence of an optimizer that looks across query blocks to generate the execution plan, the preceding query would need three scans of the base table, EMPLOYEES . This could be very inefficient. Therefore, the use of composite columns is recommended.
Oracle Database 10 g : SQL Fundamentals II 4- Concatenated Columns Concatenated groupings offer a concise way to generate useful combinations of groupings. The concatenated groupings are specified by listing multiple grouping sets, cubes, and rollups, and separating them with commas. The following is an example of concatenated grouping sets: GROUP BY GROUPING SETS(a, b), GROUPING SETS(c, d) This SQL example defines the following groupings: (a, c), (a, d), (b, c), (b, d) Concatenation of grouping sets is very helpful for these reasons: Ease of query development: You need not manually enumerate all groupings. Use by applications: SQL generated by OLAP applications often involves concatenation of grouping sets, with each grouping set defining groupings needed for a dimension.
Oracle Database 10 g : SQL Fundamentals II 4- Concatenated Groupings: Example The example on the slide results in the following groupings: (job_id, manager_id) (1) (department_id,job_id, manager_id) (2) (job_id) (3) (department_id,manager_id) (4) (department_id) (5) The total salary for each of these groups is calculated.
Oracle Database 10 g : SQL Fundamentals II 4- Summary ROLLUP and CUBE are extensions of the GROUP BY clause. ROLLUP is used to display subtotal and grand total values. CUBE is used to display cross-tabulation values. The GROUPING function enables you to determine whether a row is an aggregate produced by a CUBE or ROLLUP operator. With the GROUPING SETS syntax, you can define multiple groupings in the same query. GROUP BY computes all the groupings specified and combines them with UNION ALL . Within the GROUP BY clause, you can combine expressions in various ways: To specify composite columns, you group columns within parentheses so that the Oracle server treats them as a unit while computing ROLLUP or CUBE operations. To specify concatenated grouping sets, you separate multiple grouping sets, ROLLUP , and CUBE operations with commas so that the Oracle server combines them into a single GROUP BY clause. The result is a cross-product of groupings from each grouping set.
Oracle Database 10 g : SQL Fundamentals II 4- Practice 4: Overview In this practice, you use the ROLLUP and CUBE operators as extensions of the GROUP BY clause. You will also use GROUPING SETS .
Oracle Database 10 g : SQL Fundamentals II 4- Practice 4 1. Write a query to display the following for those employees whose manager ID is less than 120: Manager ID Job ID and total salary for every job ID for employees who report to the same manager Total salary of those managers Total salary of those managers, irrespective of the job IDs …
Oracle Database 10 g : SQL Fundamentals II 4- Practice 4 (continued) 2. Observe the output from question 1. Write a query using the GROUPING function to determine whether the NULL values in the columns corresponding to the GROUP BY expressions are caused by the ROLLUP operation. …
Oracle Database 10 g : SQL Fundamentals II 4- Practice 4 (continued) 3. Write a query to display the following for those employees whose manager ID is less than 120: Manager ID Job and total salaries for every job for employees who report to the same manager Total salary of those managers Cross-tabulation values to display the total salary for every job, irrespective of the manager Total salary irrespective of all job titles …
Oracle Database 10 g : SQL Fundamentals II 4- Practice 4 (continued) 4. Observe the output from question 3. Write a query using the GROUPING function to determine whether the NULL values in the columns corresponding to the GROUP BY expressions are caused by the CUBE operation. …
Oracle Database 10 g : SQL Fundamentals II 4- Practice 4 (continued) 5. Using GROUPING SETS , write a query to display the following groupings: department_id, manager_id, job_id department_id, job_id manager_id, job_id The query should calculate the sum of the salaries for each of these groups. … … …