Chapter 07 2
Chapter 07 2
Chapter 7
Introduction to Structured Query Language
Sections 7.7 to 7.11
1
Learning Objectives
●
Aggregate data across groups of rows
●
Create subqueries to preprocess data for inclusion in
other queries
●
Identify and use a variety of SQL functions for string,
numeric, and date manipulation
●
Explain the key principles in crafting a SELECT query
2
Aggregate Processing
●
Allows query to create summary/statistical
information
●
Basic process:
– Group rows based on certain attributes
– Use aggregate functions to produce
summary/statistical data
3
Aggregate Functions
4
Applying to the Whole Table
SELECT count(*)
FROM PRODUCT; SELECT min(p_price),
max(p_price),
avg(p_price)
SELECT count(*) FROM PRODUCT;
FROM PRODUCT
WHERE v_code = 21344;
5
COUNT: * vs. attribute
SELECT count(*)
FROM PRODUCT;
SELECT count(v_code)
FROM PRODUCT;
7
GROUP BY
●
Used to define “groupings”
●
List “grouping” attributes without aggregate
functions
– List again in GROUP BY clause
SELECT v_code,count(*) SELECT v_code,min(p_price),
FROM PRODUCT max(p_price),avg(p_price)
GROUP BY v_code; FROM PRODUCT
GROUP BY v_code;
8
Multiple Fields
●
Can use more than one field in GROUP BY
●
Can use more than one table
SELECT cus_code,inv_number,
sum(line_units*line_price)
FROM INVOICE JOIN LINE USING (INV_NUMBER)
GROUP BY cus_code,inv_number;
9
HAVING Clause
●
A WHERE clause for the grouping results
SELECT v_code,count(*)
FROM PRODUCT
GROUP BY v_code
HAVING count(*)>1;
10
Use With Column Aliases
11
Subqueries
●
Can use queries within queries
– Need to know about
– Covered more in COMP325: Advanced SQL
13
MySQL Date and Time
14
MySQL Date and Time
15
Mathematical
16
String
17
String
18
Conversion
19
Conversion
20
Relational Operators
●
UNION ●
Only work if queries
●
INTERSECT are compatible
– Need to have same
●
EXCEPT (MINUS) attribute data types in
same order
21
22