SQL: Single Table Queries GROUP BY HAVING D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 1.

Slides:



Advertisements
Similar presentations
Sorting Rows. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Construct a query to sort a results set in ascending.
Advertisements

Chapter 4 Joining Multiple Tables
1 Query-by-Example (QBE). 2 v A “GUI” for expressing queries. –Based on the Domain Relational Calulus (DRC)! –Actually invented before GUIs. –Very convenient.
Database Management Systems 3ed, Online chapter, R. Ramakrishnan and J. Gehrke1 Query-by-Example (QBE) Online Chapter Example is the school of mankind,
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Query-by-Example (QBE) Chapter 6 Example is the school of mankind, and they will learn at no.
Chapter 11 Group Functions
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
Introduction to Structured Query Language (SQL)
Introduction to Oracle9i: SQL1 SQL Group Functions.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Introduction to Structured Query Language (SQL)
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
Computer Science 101 Web Access to Databases SQL – Extended Form.
1 Section 5 - Grouping Data u The GROUP BY clause allows the grouping of data u Aggregate functions are most often used with the GROUP BY clause u GROUP.
SQL – Logical Operators and aggregation Chapter 3.2 V3.0 Napier University Dr Gordon Russell.
Chapter 2 Basic SQL SELECT Statements
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
Introduction to Databases Chapter 7: Data Access and Manipulation.
SQL/lesson 2/Slide 1 of 45 Retrieving Result Sets Objectives In this lesson, you will learn to: * Use wildcards * Use the IS NULL and IS NOT NULL keywords.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
Using Special Operators (LIKE and IN)
Grouping Data. GROUP BY clause Groups results by column name used with aggregate functions must come first when used with ORDER BY.
SQL queries ordering and grouping and joins
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
SQL-5 (Group By.. Having). Group By  Need: To apply the aggregate functions to subgroups of tuples in a relation, where the subgroups are based on some.
BACS 287 Structured Query Language 1. BACS 287 Visual Basic Table Access Visual Basic provides 2 mechanisms to access data in tables: – Record-at-a-time.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Indexes and Views Unit 7.
1 DBS201: More on SQL Lecture 3. 2 Agenda How to use SQL to update table definitions How to update data in a table How to join tables together.
Displaying Data from Multiple Tables (SQL99 Syntax with examples)
CSCI N311: Oracle Database Programming 4-1 Chapter 12: When One Query Depends Upon Another Correlated Subqueries. Subqueries in the where clause. Anti-Joins.
SQL: Join Training Problems D. Christozov / G.Tuparov INF 280 Database Systems: SQL – Join Training Problems 1.
Grouping Data Steve Perry
SQL: Sets UNION INTERSECT MINUS D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Sets 1.
SQL: Sub-queries Single-value sub-queries Single-column sub-queries Sub-queries that produce tables Correlated sub-queries D. Christozov / G.Tuparov INF.
INF 280 Database Systems SQL:Join
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
SQL: Single Table Queries SELECT FROM WHERE ORDER D. Christozov / G.Tuparov INF 280 Database Systems: Single Table Queries 1.
CS 3630 Database Design and Implementation. Base Table and View Base Table Stored on disk View Virtual table Records are not stored on disk Query is stored.
April 2002 Information Systems Design John Ogden & John Wordsworth 1 Database Design SQL (1) John Wordsworth Department of Computer Science The University.
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Relational Databases Today we will look at: Different ways of searching a database Creating queries Aggregate Queries More complex queries involving different.
IFS180 Intro. to Data Management Chapter 10 - Unions.
Connect to SQL Server and run select statements
CS 3630 Database Design and Implementation
References: Text Chapters 8 and 9
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
SQL FUNDAMENTALS CDSE Days 2018.
Writing Basic SQL SELECT Statements
MENAMPILKAN DATA DARI SATU TABEL (Chap 2)
SQL – Entire Select.
Chapter 4 Summary Query.
CS 3630 Database Design and Implementation
Access: SQL Participation Project
Writing Basic SQL SELECT Statements
Structured Query Language – The Fundamentals
Section 4 - Sorting/Functions
Databases Continued 10/18/05.
Group Operations Part IV.
Presentation transcript:

SQL: Single Table Queries GROUP BY HAVING D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 1

Select: syntax SELECT [ DISTINCT | ALL ]{ * | column_list } FROM [owner.]table_name [alias] [,[owner.]table_name [alias]]... [WHERE condition] [GROUP BY column_list] [HAVING condition] [ORDER BY column_list]; Can accomplish the three relational operations: selection, projection, and join. The order of the clauses in the SELECT statement cannot be changed. The only required clauses are SELECT and FROM. D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 2

The GROUP BY clause Defines groups of output rows to which aggregate functions can be applied. There are restriction for the SELECT list, when GROUP BY is used: this list MUST include only fields that have a single value per group (only fields mentioned in GROUP BY clause or aggregate functions). In many dialects GROUP BY also order the result according to specified fields, applying the same rules as for ORDER BY. WHERE clause is applied first than groups are formed according to the remaining rows. D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 3

The GROUP BY clause (cont.) The 1989’ standard allows a single level grouping. The 1992’s introduces multi-level grouping (or more than one field can be used; the mechanism of major and minor keys is used). D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 4

The HAVING clause Just as the WHERE clause defines a filter, but on the aggregate group values. Only column names used in clause HAVING may appear in GROUP BY list OR aggregate functions. In general, the expressions must be single valued per group. D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 5

The HAVING clause (cont.) HAVING and WHERE can be used interchangeable if HAVING does not include aggregate functions. HAVING and WHERE cannot be used interchangeable, when:  the filter-condition includes aggregate functions;  the filter-condition deals with individual rows rather than groups of rows;  combined WHERE and HAVING are required. D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 6

Group by: illustration cust_idquantity AAA10 BBB20 AAA30 CCC40 BBB50 AAA60 AAA70 EEE20 CCC40 BBB60 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 7 cust_idquantity AAA10 AAA30 AAA60 AAA70 BBB20 BBB50 BBB60 CCC40 CCC40 EEE20 SELECT cust_id, SUM(quantity) AS QNTY FROM orders GROUP BY cust_id cust_idQNTY AAA170 BBB130 CCC80 EEE20

Group by: illustration D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 8 cust_idQNTY AAA170 BBB130 CCC80 EEE20 SELECT Cust_id, SUM(quantity) AS QNTY FROM Orders GROUP BY Cust_id HAVING SUM(quantity) > 100 cust_idQNTY AAA170 BBB130

Examples: Table CSupplier (1) CodeNamePriceDealerDnameDcodeDpriceDphoneDPNameDQntyDDate 1X15.00DGCDimitarD P X15.00VKVolinV Stoka X15.00JGJohnJ Good X26.00DGCDimitarD P X26.00VKVolinV Stoka X37.00DGCDimitarD P X37.00JGJohnJ Good D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 9 Write SQL SELECT statement to calculate the income (sum(Dprice*DQnty) ) received from every dealer.

Examples: Table CSupplier (2) CodeNamePriceDealerDnameDcodeDpriceDphoneDPNameDQntyDDate 1X15.00DGCDimitarD P X15.00VKVolinV Stoka X15.00JGJohnJ Good X26.00DGCDimitarD P X26.00VKVolinV Stoka X37.00DGCDimitarD P X37.00JGJohnJ Good D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 10 Write SQL SELECT statement to calculate the income (sum(Dprice*DQnty) ) received every day.

Examples: Table CSupplier (3) CodeNamePriceDealerDnameDcodeDpriceDphoneDPNameDQntyDDate 1X15.00DGCDimitarD P X15.00VKVolinV Stoka X15.00JGJohnJ Good X26.00DGCDimitarD P X26.00VKVolinV Stoka X37.00DGCDimitarD P X37.00JGJohnJ Good D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 11 Write SQL SELECT statement to calculate the income (sum(Dprice*DQnty) ) received for every product.

Examples: Table CSupplier (4) CodeNamePriceDealerDnameDcodeDpriceDphoneDPNameDQntyDDate 1X15.00DGCDimitarD P X15.00VKVolinV Stoka X15.00JGJohnJ Good X26.00DGCDimitarD P X26.00VKVolinV Stoka X37.00DGCDimitarD P X37.00JGJohnJ Good D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 12 What the following query will print out: SELECT Code, DDate, SUM(DPrice*DQnty) AS Money FROM CSupplier WHERE Dealer <> ‘jg’ GROUP BY Code, DDate;

Examples: Table CSupplier (5) CodeNamePriceDealerDnameDcodeDpriceDphoneDPNameDQntyDDate 1X15.00DGCDimitarD P X15.00VKVolinV Stoka X15.00JGJohnJ Good X26.00DGCDimitarD P X26.00VKVolinV Stoka X37.00DGCDimitarD P X37.00JGJohnJ Good D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 13 What the following query will print out: SELECT Dealer, Dcode, SUM(DPrice*DQnty) AS Money FROM CSupplier GROUP BY Dealer, Dcode HAVING Money < 5.00;

Examples: Table CSupplier (6) CodeNamePriceDealerDnameDcodeDpriceDphoneDPNameDQntyDDate 1X15.00DGCDimitarD P X15.00VKVolinV Stoka X15.00JGJohnJ Good X26.00DGCDimitarD P X26.00VKVolinV Stoka X37.00DGCDimitarD P X37.00JGJohnJ Good D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 14 What the following query will print out: SELECT Code, Dcode, SUM(DPrice*DQnty) AS Money FROM CSupplier WHERE Dname <> ‘John’ GROUP BY Code, Dcode;

Examples: Table HomeDeliveryPizzas (1) Order_idPizza_idQuantityIngr_idDescrUnitAmountI_priceNameAddressPrice Tomato sauceM DGCSofia CheeseSm DGCSofia DressingL DGCSofia Tomato sauceM VKAUBG CheeseSm1.00 VKAUBG HamKg JGScapto SausageM JGScapto6.00 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 15 Write SQL SELECT statement to evaluate the taste of consumers. Tip: “taste” is the combinations of pizza (Pizza_id) and ingredient (Ingr_id) and you have to count them.

Examples: Table HomeDeliveryPizzas (2) Order_idPizza_idQuantityIngr_idDescrUnitAmountI_priceNameAddressPrice Tomato sauceM DGCSofia CheeseSm DGCSofia DressingL DGCSofia Tomato sauceM VKAUBG CheeseSm1.00 VKAUBG HamKg JGScapto SausageM JGScapto6.00 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 16 Write SQL SELECT statement to evaluate the profitability by address.

Examples: Table HomeDeliveryPizzas (3) Order_idPizza_idQuantityIngr_idDescrUnitAmountI_priceNameAddressPrice Tomato sauceM DGCSofia CheeseSm DGCSofia DressingL DGCSofia Tomato sauceM VKAUBG CheeseSm1.00 VKAUBG HamKg JGScapto SausageM JGScapto6.00 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 17 Write SQL SELECT statement to calculate the income generated by every ingredient (Sum(Amount*I_price) ).

Examples: Table HomeDeliveryPizzas (4) Order_idPizza_idQuantityIngr_idDescrUnitAmountI_priceNameAddressPrice Tomato sauceM DGCSofia CheeseSm DGCSofia DressingL DGCSofia Tomato sauceM VKAUBG cheeseSm1.00 VKAUBG HamKg JGScapto SausageM JGScapto6.00 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 18 What the following queries will print out: SELECT Pizza_id, Ingr_id, Descr, Sum(Amount*I_price) AS Money FROM HDPizzas WHERE Pizza_id <> 124 GROUP BY Pizza_id, Ingr_id, Descr;

Examples: Table HomeDeliveryPizzas (5) Order_idPizza_idQuantityIngr_idDescrUnitAmountI_priceNameAddressPrice Tomato sauceM DGCSofia CheeseSm DGCSofia DressingL DGCSofia Tomato sauceM VKAUBG cheeseSm1.00 VKAUBG HamKg JGScapto SausageM JGScapto6.00 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 19 What the following queries will print out: SELECT Pizza_id, Ingr_id, Sum(Amount) AS Used FROM HDPizzas GROUP BY Pizza_id, Ingr_id ORDER BY 3;

Examples: Table HomeDeliveryPizzas (6) Order_idPizza_idQuantityIngr_idDescrUnitAmountI_priceNameAddressPrice Tomato sauceM DGCSofia CheeseSm DGCSofia DressingL DGCSofia Tomato sauceM VKAUBG CheeseSm1.00 VKAUBG HamKg JGScapto SausageM JGScapto6.00 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 20 What the following queries will print out: SELECT Pizza_id, Address, Count(*) AS Used FROM HDPizzas GROUP BY Pizza_id, Address ORDER BY Address;

Examples: Table Booking (1) Hotel_idRoom_NumberRoom_typeDate_fromDate_toPrice AAA100Double AAA101Double AAA102Double BBB200SingleNull AAA205Apartment AAA210SingleNull BBB550Double BBB312Single D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 21 Write the SQL query to list the number of rooms by type, booked for March or April, 2014.

Examples: Table Booking (2) Hotel_idRoom_NumberRoom_typeDate_fromDate_toPrice AAA100Double AAA101Double AAA102Double BBB200SingleNull AAA205Apartment AAA210SingleNull BBB550Double BBB312Single D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 22 Write the SQL query to list the income expected by any of the hotels in May.

Examples: Table Booking (3) Hotel_idRoom_NumberRoom_typeDate_fromDate_toPrice AAA100Double AAA101Double AAA102Double BBB200SingleNull AAA205Apartment AAA210SingleNull BBB550Double BBB312Single D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 23 Write the SQL query to list the daily average income, expected from every type of room booked for March or April, 2014.

Examples: Table Booking (4) Hotel_idRoom_NumberRoom_typeDate_fromDate_toPrice AAA100Double AAA101Double AAA102Double BBB200SingleNull AAA205Apartment AAA210SingleNull BBB550Double BBB312Single D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 24 What the following queries will print out: SELECT Hotel_id, SUM(Price) FROM Booking WHERE Date_from IS NOT Null GROUP BY Hotel_id ORDER BY 2 DESC;

Examples: Table Booking (5) Hotel_idRoom_NumberRoom_typeDate_fromDate_toPrice AAA100Double AAA101Double AAA102Double BBB200SingleNull AAA205Apartment AAA210SingleNull BBB550Double BBB312Single D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 25 What the following queries will print out: SELECT Room_type, SUM(Price) FROM Booking WHERE Date_from IS NOT Null GROUP BY Room_type HAVING Room_type IN ('Single', 'Double') ORDER BY 2 DESC;

Examples: Table Booking (6) Hotel_idRoom_NumberRoom_typeDate_fromDate_toPrice AAA100Double AAA101Double AAA102Double BBB200SingleNull AAA205Apartment AAA210SingleNull BBB550Double BBB312Single D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 26 What the following queries will print out: SELECT Room_type, Count(*) FROM Booking WHERE Date_from IS NOT Null GROUP BY Room_type HAVING Room_type <> 'Single' ORDER BY 2 DESC;

Examples: Table Booking (7) Hotel_idRoom_NumberRoom_typeDate_fromDate_toPrice AAA100Double AAA101Double AAA102Double BBB200SingleNull AAA205Apartment AAA210SingleNull BBB550Double BBB312Single D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 27 What the following queries will print out: SELECT Room_type, SUM(Price) FROM Booking WHERE Date_from IS NOT Null and Hotel_id = 'AAA' GROUP BY Room_type HAVING AVG(Price) > 100 ORDER BY 2 DESC;

Examples: table Vehicles – claims (1) V_idDate_SoldC_idCdateCostMileagePart C P C P C P C P325 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 28 Write a query to list vehicles with a single claim only.

Examples: table Vehicles – claims (2) V_idDate_SoldC_idCdateCostMileagePart C P C P C P C P325 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 29 Write a query to list vehicles with multiple claims only.

Examples: table Vehicles – claims (4) V_idDate_SoldC_idCdateCostMileagePart C P C P C P C P325 D. Christozov / G.Tuparov INF 280 Database Systems: SQL - Single Table queries 30 For vehicles with multiple claims, calculate the mileage accumulation before the first claim.