SlideShare una empresa de Scribd logo
1 de 4
SQL Simple Queries – Worksheet 3


                              SQL Queries - Basics
                                     Worksheet - 3
                                      SUMMARY QUERIES
1     What is a summary query?
      For certain queries we are not interested in finer details of each record in a table. Rather we
      want aggregate or summary information. For example, consider the following queries:
      a) How many salespeople have exceeded their yearly quota?
      b) What is the sixe of the average order for an office?
      c) How many salespeople are assigned to each office?
      d) What is the average mark of students in an exam?

      SQL supports these requests for summary data through column functions and the GROUP
      BY and HAVING clauses of the SELECT statement.

2     What are the COLUMN functions in SQL?
      SQL lets you summarize data from the database through a set of column functions. A SQL
      column function takes an entire column of data as its argument and produces a single data
      item that summarizes the column.

      For example, the AVG() column function takes a column of data and computes its average.

      Here is a query that uses the AVG() column function to compute the average value of two
      columns from the SALESREPS table:

      What are the average quota and average sales of our salespeople?

      SELECT AVG(QUOTA), AVG(SALES)
      FROM SALESREPS
      AVG(QUOTA)   AVG(SALES)

      The first column function in the query takes values in the QUOTA column and computes
      their average; the second one averages the values in the SALES column. The query
      produces a single row of query results summarizing the data in the SALESREPS table.

      SQL offers 6 different column functions. These are:

      1.   SUM()             – computes the total of a column
      2.   AVG()             – computes the average value in a column
      3.   MIN()             – finds the minimum value in a column
      4.   MAX()             – finds the maximum value in a column
      5.   COUNT()           – counts the number of values in a column
      6.   COUNT(*)          – counts row of query results

      The argument to a column function can be a simple column name or an expression.

      Example 1:
Prof. Mukesh N. Tekwani                                                                  Page 1 of 4
SQL Simple Queries – Worksheet 3

     What is the average quota performance of our salespeople?

     SELECT AVG (100 * (SALES/QUOTA))
     FROM SALESREPS

     Computing a column total

     The SUM() column function computes the sum of a column of data values. The data in the
     column must have a numeric type (integer, decimal, floating point, or money). The result of
     the SUM() function has the same basic data type as the data in the column, but the result
     may have a higher precision. For example, if you apply the SUM() function to a column of
     16-bit integers, it may produce a 32-bit integer as its result.

     Example 2:

     What are the total quotas and sales for all salespeople?

     SELECT SUM(QUOTA), SUM(SALES)
     FROM SALESREPS

     What is the total of the orders taken by Bill Adams?

     SELECT SUM(AMOUNT)
     FROM ORDERS, SALESREPS
     WHERE NAME = 'Bill Adams'
     AND REP = EMPL_NUM

     Computing an Average

     The AVG() column function computes the average of a column of data values. The data in
     the column must have a numeric type.

     Because the AVG() function adds the values in the column and then divides by the number
     of values, its result may have a different data type than that of the values in the column. For
     example, if you apply the AVG() function to a column of integers, the result will be either
     a decimal or a floating point number.

     Calculate the average price of products from manufacturer ACI.

     SELECT AVG(PRICE)
     FROM PRODUCTS
     WHERE MFR_ID = 'ACI'

     Calculate the average size of an order placed by Acme Mfg. (customer number 2103).

     SELECT AVG(AMOUNT)
     FROM ORDERS
     WHERE CUST = 2103

Page 2 of 4                                                           mukeshtekwani@hotmail.com
SQL Simple Queries – Worksheet 3

      Finding maximum and minimum values

      The MIN() and MAX() column functions find the smallest and largest values in a column,
      respectively. The data in the column can contain numeric, string, or date/time information.
      The result of the MIN() or MAX() function has exactly the same data type as the data in
      the column.


      What are the smallest and largest assigned quotas?
      SELECT MIN(QUOTA), MAX(QUOTA)
      FROM SALESREPS

      What is the earliest order date in the database?

      SELECT MIN(ORDER_DATE)
      FROM ORDERS

      What is the best sales performance of any salesperson?

      SELECT MAX(100 * (SALES/QUOTA))
      FROM SALESREPS
      MAX(100*(SALES/QUOTA))

      Counting Data Values
      The COUNT() column function counts the number of data values in a column. The data in
      the column can be of any type. The COUNT() function always returns an integer,
      regardless of the data type of the column.

      How many customers are there?
      SELECT COUNT(CUST_NUM)
      FROM CUSTOMERS


      How many salespeople are over quota?

      SELECT COUNT(NAME)
      FROM SALESREPS
      WHERE SALES > QUOTA

      Find the average order amount, total order amount, average order amount as a percentage
      of the customer's credit limit, and average order amount as a percentage of the
      salesperson's quota.

      SELECT AVG(AMOUNT), SUM(AMOUNT),
      (100 * AVG(AMOUNT/CREDIT_LIMIT)),
      (100 * AVG(AMOUNT/QUOTA))
      FROM ORDERS, CUSTOMERS, SALESREPS
      WHERE CUST = CUST_NUM
      AND REP = EMPL_NUM
Prof. Mukesh N. Tekwani                                                              Page 3 of 4
SQL Simple Queries – Worksheet 3


3    What are Subqueries?
     Subqueries are query statements inside of query statements. Like the order of operations in
     algebra, order of operations also come into play when you start to embed SQL commands
     inside of other SQL commands (subqueries).

     Example 1:
     Select only the most recent order(s) in the orders table.

     We use the MAX(). This function wraps around a table column and returns the current
     highest (max) value for the specified column. We use this function to return the current
     "highest", or most recent date value in the orders table.

     USE mydatabase;
     SELECT MAX(day_of_order)
     FROM orders

     Now we can throw this query into the WHERE clause of another SELECT query.

     USE mydatabase;
     SELECT *
     FROM orders
     WHERE day_of_order = ( SELECT MAX(day_of_order) FROM orders )

4    SELECT Case statement
     SQL CASE is a very unique conditional statement providing if/then/else logic for any
     ordinary SQL command, such as SELECT or UPDATE. It then provides when-then-else
     functionality (WHEN this condition is met THEN do_this).

     USE northwind

     SELECT productid,
           'Status' = CASE
             WHEN quantity > 0 THEN 'in stock'
             ELSE 'out of stock'
             END
     FROM "order details";

5    GROUP BY statement
     SQL GROUP BY aggregates (consolidates and calculates) column values into a single
     record value. GROUP BY requires a list of table columns on which to run the calculations.

     USE mydatabase
     SELECT customer
     FROM orders

     GROUP BY customer




Page 4 of 4                                                         mukeshtekwani@hotmail.com

Más contenido relacionado

La actualidad más candente

Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sqlCharan Reddy
 
80 different SQL Queries with output
80 different SQL Queries with output80 different SQL Queries with output
80 different SQL Queries with outputNexus
 
Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testerstlvd
 
Group By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQLGroup By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQLMSB Academy
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan PasrichaMananPasricha
 
06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinctBishal Ghimire
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQLCoT
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive TechandMate
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 

La actualidad más candente (20)

Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sql
 
Sql alias
Sql aliasSql alias
Sql alias
 
80 different SQL Queries with output
80 different SQL Queries with output80 different SQL Queries with output
80 different SQL Queries with output
 
Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testers
 
Group By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQLGroup By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQL
 
Sql joins
Sql joinsSql joins
Sql joins
 
SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
Sql select
Sql select Sql select
Sql select
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL
SQLSQL
SQL
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
 
SQL
SQLSQL
SQL
 
06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinct
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
SQL Differences SQL Interview Questions
SQL Differences  SQL Interview QuestionsSQL Differences  SQL Interview Questions
SQL Differences SQL Interview Questions
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 

Destacado

Applied 20S January 23, 2009
Applied 20S January 23, 2009Applied 20S January 23, 2009
Applied 20S January 23, 2009Darren Kuropatwa
 
Insediarsi in AREA Science Park
Insediarsi in AREA Science ParkInsediarsi in AREA Science Park
Insediarsi in AREA Science ParkAREA Science Park
 
Gallatin Thesis '15
Gallatin Thesis '15Gallatin Thesis '15
Gallatin Thesis '15Emma Behnke
 
The Future of Learning and Learning for the Future
The Future of Learning and Learning for the FutureThe Future of Learning and Learning for the Future
The Future of Learning and Learning for the FutureKim Flintoff
 
Huong dan dang ky
Huong dan dang kyHuong dan dang ky
Huong dan dang kyHavy Tran
 
Personal branding(with speaking notes)
Personal branding(with speaking notes)Personal branding(with speaking notes)
Personal branding(with speaking notes)Mani Nutulapati
 
03 424 private club
03 424 private club03 424 private club
03 424 private clubLin, Tony
 
Entorno gráfico word
Entorno gráfico wordEntorno gráfico word
Entorno gráfico wordzanethpineda
 
CETWorld- Mobile MediaCrossMedia
CETWorld- Mobile MediaCrossMediaCETWorld- Mobile MediaCrossMedia
CETWorld- Mobile MediaCrossMediaMatthew Snyder
 

Destacado (15)

From hear to there
From hear to thereFrom hear to there
From hear to there
 
Applied 20S January 23, 2009
Applied 20S January 23, 2009Applied 20S January 23, 2009
Applied 20S January 23, 2009
 
Insediarsi in AREA Science Park
Insediarsi in AREA Science ParkInsediarsi in AREA Science Park
Insediarsi in AREA Science Park
 
Gallatin Thesis '15
Gallatin Thesis '15Gallatin Thesis '15
Gallatin Thesis '15
 
Escuelas economicas
Escuelas economicasEscuelas economicas
Escuelas economicas
 
1
11
1
 
The Future of Learning and Learning for the Future
The Future of Learning and Learning for the FutureThe Future of Learning and Learning for the Future
The Future of Learning and Learning for the Future
 
Huong dan dang ky
Huong dan dang kyHuong dan dang ky
Huong dan dang ky
 
Personal branding(with speaking notes)
Personal branding(with speaking notes)Personal branding(with speaking notes)
Personal branding(with speaking notes)
 
03 424 private club
03 424 private club03 424 private club
03 424 private club
 
All about you
All about youAll about you
All about you
 
Entorno gráfico word
Entorno gráfico wordEntorno gráfico word
Entorno gráfico word
 
CETWorld- Mobile MediaCrossMedia
CETWorld- Mobile MediaCrossMediaCETWorld- Mobile MediaCrossMedia
CETWorld- Mobile MediaCrossMedia
 
Niña hechizera
Niña hechizeraNiña hechizera
Niña hechizera
 
Sosial læring 141118
Sosial læring 141118Sosial læring 141118
Sosial læring 141118
 

Similar a Sql wksht-3

Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdfKalyankumarVenkat1
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptxSabrinaShanta2
 
ADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptxADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptxArjayBalberan1
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence PortfolioChris Seebacher
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)Huda Alameen
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
 
Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfhowto4ucontact
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQueryAbhishek590097
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
Simplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsSimplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsClayton Groom
 
Key functions in_oracle_sql
Key functions in_oracle_sqlKey functions in_oracle_sql
Key functions in_oracle_sqlpgolhar
 
Ground Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planGround Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planMaria Colgan
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sqlMcNamaraChiwaye
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfDraguClaudiu
 
Intro to tsql unit 3
Intro to tsql   unit 3Intro to tsql   unit 3
Intro to tsql unit 3Syed Asrarali
 
Intro To TSQL - Unit 3
Intro To TSQL - Unit 3Intro To TSQL - Unit 3
Intro To TSQL - Unit 3iccma
 

Similar a Sql wksht-3 (20)

Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdf
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek SharmaIntroduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptx
 
ADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptxADV Powepoint 3 Lec.pptx
ADV Powepoint 3 Lec.pptx
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic Functions
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdf
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Simplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsSimplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functions
 
Key functions in_oracle_sql
Key functions in_oracle_sqlKey functions in_oracle_sql
Key functions in_oracle_sql
 
Ground Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planGround Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_plan
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
Intro to tsql unit 3
Intro to tsql   unit 3Intro to tsql   unit 3
Intro to tsql unit 3
 
Intro To TSQL - Unit 3
Intro To TSQL - Unit 3Intro To TSQL - Unit 3
Intro To TSQL - Unit 3
 

Más de Mukesh Tekwani

ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 
TCP-IP Reference Model
TCP-IP Reference ModelTCP-IP Reference Model
TCP-IP Reference ModelMukesh Tekwani
 

Más de Mukesh Tekwani (20)

Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 
Social media
Social mediaSocial media
Social media
 
TCP-IP Reference Model
TCP-IP Reference ModelTCP-IP Reference Model
TCP-IP Reference Model
 

Último

Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 

Último (20)

Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 

Sql wksht-3

  • 1. SQL Simple Queries – Worksheet 3 SQL Queries - Basics Worksheet - 3 SUMMARY QUERIES 1 What is a summary query? For certain queries we are not interested in finer details of each record in a table. Rather we want aggregate or summary information. For example, consider the following queries: a) How many salespeople have exceeded their yearly quota? b) What is the sixe of the average order for an office? c) How many salespeople are assigned to each office? d) What is the average mark of students in an exam? SQL supports these requests for summary data through column functions and the GROUP BY and HAVING clauses of the SELECT statement. 2 What are the COLUMN functions in SQL? SQL lets you summarize data from the database through a set of column functions. A SQL column function takes an entire column of data as its argument and produces a single data item that summarizes the column. For example, the AVG() column function takes a column of data and computes its average. Here is a query that uses the AVG() column function to compute the average value of two columns from the SALESREPS table: What are the average quota and average sales of our salespeople? SELECT AVG(QUOTA), AVG(SALES) FROM SALESREPS AVG(QUOTA) AVG(SALES) The first column function in the query takes values in the QUOTA column and computes their average; the second one averages the values in the SALES column. The query produces a single row of query results summarizing the data in the SALESREPS table. SQL offers 6 different column functions. These are: 1. SUM() – computes the total of a column 2. AVG() – computes the average value in a column 3. MIN() – finds the minimum value in a column 4. MAX() – finds the maximum value in a column 5. COUNT() – counts the number of values in a column 6. COUNT(*) – counts row of query results The argument to a column function can be a simple column name or an expression. Example 1: Prof. Mukesh N. Tekwani Page 1 of 4
  • 2. SQL Simple Queries – Worksheet 3 What is the average quota performance of our salespeople? SELECT AVG (100 * (SALES/QUOTA)) FROM SALESREPS Computing a column total The SUM() column function computes the sum of a column of data values. The data in the column must have a numeric type (integer, decimal, floating point, or money). The result of the SUM() function has the same basic data type as the data in the column, but the result may have a higher precision. For example, if you apply the SUM() function to a column of 16-bit integers, it may produce a 32-bit integer as its result. Example 2: What are the total quotas and sales for all salespeople? SELECT SUM(QUOTA), SUM(SALES) FROM SALESREPS What is the total of the orders taken by Bill Adams? SELECT SUM(AMOUNT) FROM ORDERS, SALESREPS WHERE NAME = 'Bill Adams' AND REP = EMPL_NUM Computing an Average The AVG() column function computes the average of a column of data values. The data in the column must have a numeric type. Because the AVG() function adds the values in the column and then divides by the number of values, its result may have a different data type than that of the values in the column. For example, if you apply the AVG() function to a column of integers, the result will be either a decimal or a floating point number. Calculate the average price of products from manufacturer ACI. SELECT AVG(PRICE) FROM PRODUCTS WHERE MFR_ID = 'ACI' Calculate the average size of an order placed by Acme Mfg. (customer number 2103). SELECT AVG(AMOUNT) FROM ORDERS WHERE CUST = 2103 Page 2 of 4 mukeshtekwani@hotmail.com
  • 3. SQL Simple Queries – Worksheet 3 Finding maximum and minimum values The MIN() and MAX() column functions find the smallest and largest values in a column, respectively. The data in the column can contain numeric, string, or date/time information. The result of the MIN() or MAX() function has exactly the same data type as the data in the column. What are the smallest and largest assigned quotas? SELECT MIN(QUOTA), MAX(QUOTA) FROM SALESREPS What is the earliest order date in the database? SELECT MIN(ORDER_DATE) FROM ORDERS What is the best sales performance of any salesperson? SELECT MAX(100 * (SALES/QUOTA)) FROM SALESREPS MAX(100*(SALES/QUOTA)) Counting Data Values The COUNT() column function counts the number of data values in a column. The data in the column can be of any type. The COUNT() function always returns an integer, regardless of the data type of the column. How many customers are there? SELECT COUNT(CUST_NUM) FROM CUSTOMERS How many salespeople are over quota? SELECT COUNT(NAME) FROM SALESREPS WHERE SALES > QUOTA Find the average order amount, total order amount, average order amount as a percentage of the customer's credit limit, and average order amount as a percentage of the salesperson's quota. SELECT AVG(AMOUNT), SUM(AMOUNT), (100 * AVG(AMOUNT/CREDIT_LIMIT)), (100 * AVG(AMOUNT/QUOTA)) FROM ORDERS, CUSTOMERS, SALESREPS WHERE CUST = CUST_NUM AND REP = EMPL_NUM Prof. Mukesh N. Tekwani Page 3 of 4
  • 4. SQL Simple Queries – Worksheet 3 3 What are Subqueries? Subqueries are query statements inside of query statements. Like the order of operations in algebra, order of operations also come into play when you start to embed SQL commands inside of other SQL commands (subqueries). Example 1: Select only the most recent order(s) in the orders table. We use the MAX(). This function wraps around a table column and returns the current highest (max) value for the specified column. We use this function to return the current "highest", or most recent date value in the orders table. USE mydatabase; SELECT MAX(day_of_order) FROM orders Now we can throw this query into the WHERE clause of another SELECT query. USE mydatabase; SELECT * FROM orders WHERE day_of_order = ( SELECT MAX(day_of_order) FROM orders ) 4 SELECT Case statement SQL CASE is a very unique conditional statement providing if/then/else logic for any ordinary SQL command, such as SELECT or UPDATE. It then provides when-then-else functionality (WHEN this condition is met THEN do_this). USE northwind SELECT productid, 'Status' = CASE WHEN quantity > 0 THEN 'in stock' ELSE 'out of stock' END FROM "order details"; 5 GROUP BY statement SQL GROUP BY aggregates (consolidates and calculates) column values into a single record value. GROUP BY requires a list of table columns on which to run the calculations. USE mydatabase SELECT customer FROM orders GROUP BY customer Page 4 of 4 mukeshtekwani@hotmail.com