Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Query Language (II) (結構化查詢語言)

Similar presentations


Presentation on theme: "Structured Query Language (II) (結構化查詢語言)"— Presentation transcript:

1 Structured Query Language (II) (結構化查詢語言)
SQL Structured Query Language (II) (結構化查詢語言) 2018/12/1

2 SQL query – Grouping SELECT ...... FROM ...... WHERE condition
GROUP BY groupexpr [HAVING requirement] Group functions: COUNT( ), SUM( ), AVG( ), MAX( ), MIN( ) – groupexpr specifies the related rows to be grouped as one entry. Usually it is a column. – WHERE condition specifies the condition of individual rows before the rows are group. HAVING requirement specifies the condition involving the whole group. 2018/12/1

3 Example field type width contents id numeric 4 student id number
Table: stud field type width contents id numeric student id number name character name dob date date of birth sex character sex: M / F class character class hcode character house code: R, Y, B, G dcode character district code remission logical fee remission (學費減免) mtest numeric Math test score 2018/12/1

4 1A 1A 1B 1C 1B 1C Group By Class COUNT( ) COUNT( ) COUNT( )
e.g.1 List the number of students of each class. Group By Class Stud class 1A 1B 1C 1A 1A 1B 1C COUNT( ) COUNT( ) 1B COUNT( ) 1C 2018/12/1

5 Grouping SELECT class, COUNT(*) FROM stud GROUP BY class
eg. 1 List the number of students of each class. SELECT class, COUNT(*) FROM stud GROUP BY class Result 2018/12/1

6 Grouping SELECT class, Round(AVG(mtest),2) FROM stud GROUP BY class
e.g. 2 List the average Math test score of each class. SELECT class, Round(AVG(mtest),2) FROM stud GROUP BY class Result 2018/12/1

7 Grouping SELECT dcode, COUNT(*) FROM stud WHERE sex=‘F’ GROUP BY dcode
e.g. 3 List the number of girls of each district. SELECT dcode, COUNT(*) FROM stud WHERE sex=‘F’ GROUP BY dcode Result 2018/12/1

8 Grouping SELECT MAX(mtest), MIN(mtest), dcode FROM stud
e.g. 4 List the max. and min. test score of Form 1 students of each district. SELECT MAX(mtest), MIN(mtest), dcode FROM stud WHERE class LIKE ‘1_’ GROUP BY dcode Result 2018/12/1

9 Grouping SELECT AVG(mtest), class FROM stud WHERE sex=‘M’
e.g. 5 List the average Math test score of the boys in each class. The list should not contain class with less than 3 boys. SELECT AVG(mtest), class FROM stud WHERE sex=‘M’ GROUP BY class HAVING COUNT(*) >= 3 Result 2018/12/1

10 Grouping 2018/12/1

11 Multiple Tables – Join by Columns:
SQL provides a convenient operation to retrieve information from multiple tables. This operation is called Join (接合) The join operation will combine the tables into one large table by columns (欄) An Inner Join is a join operation that joins two tables by their common column (共通欄) It combines records from two tables only if the values of the joined fields meet a specified condition. The join operation is also called Equi-Join 2018/12/1

12 1. Inner Join (內接合) – Syntax
SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a, table2 b ; WHERE a.comcol = b.comcol and filterCondition 2018/12/1

13 Table : d_play_list_items Table : d_track_listings
1. Equi-Join / Inner Join Table : d_play_list_items Table : d_track_listings 2018/12/1

14 Example: Music Instrument learnt by students
Table: stud field type width contents id numeric student id number name character name dob date date of birth sex character sex: M / F class character class hcode character house code: R, Y, B, G dcode character district code remission logical fee remission (學費減免) mtest numeric Math test score Table: music field type width contents id numeric student id number type character type of the music instrument 2018/12/1 Join by The common field: id

15 they learn. (Inner Join)
eg.1 Make a list of students and the instruments they learn. (Inner Join) Student 9801 id name class Music id 9801 type Same id Join 9801 Product id name class type 2018/12/1

16 they learn. (Inner Join)
eg.1 Make a list of students and the instruments they learn. (Inner Join) SELECT s.class, s.name, s.id, m.type FROM stud s, music m WHERE s.id=m.id ORDER BY class, name Result 2018/12/1

17 (2) Condition: m.type="Piano" (3) GROUP BY class
eg.2 Find the number of students learning piano in each class. Three Parts : (1) Inner Join. (2) Condition: m.type="Piano" (3) GROUP BY class 2018/12/1

18 in each class. eg.2 Find the number of students learning piano Join
Music Student Join Product Condition m.type= "Piano" Group By class 2018/12/1

19 SELECT s.class, COUNT(*) FROM stud s, music m
eg.2 Find the number of students learning piano in each class. SELECT s.class, COUNT(*) FROM stud s, music m WHERE s.id=m.id AND m.type=‘Piano’ GROUP BY class ORDER BY class Result 2018/12/1

20 Other Examples of Inner Join
In a DBMS of a Musical Instrumental Co. , 3 tables are used: Salorder m m Client 1 1 Salstaff 2018/12/1

21 SELECT O.order_no, C.client, C.name FROM salOrder O, Client C
e.g1 Display the names of the contact person and client, corresponding to the same order. (Two Tables) SELECT O.order_no, C.client, C.name FROM salOrder O, Client C WHERE O.client_id =C.client_id Result 2018/12/1

22 SELECT O.order_no, S.name as salesperson, O.order_date
e.g.2 Display the sales orders made between May and June , with the corresponding salespersons in the same cursor (list by date). SELECT O.order_no, S.name as salesperson, O.order_date FROM salOrder O, salStaff S WHERE O.staff_id=S.staff_id and order_date between '1-5月-2006' and '30-6月-2006' ORDER BY 3 Result 2018/12/1

23 e.g.3 Display the names of the contact person , client and the
salesperson corresponding to the same sales order. (3 Tables) SELECT O.order_no, C.client, C.name as contact, S.name as salesperson FROM salOrder O, client C, salStaff S WHERE O.staff_id=S.staff_id and O.client_id=C.client_id From salOrder From client From client From salStaff Result 2018/12/1

24 2. Nonequi-Join SELECT d_packages.code, d_events.cost
FROM d_packages, d_events WHERE d_events.cost BETWEEN d_packages.low_range AND d_packages.high_range 2018/12/1

25 3. Outer Join (外接合) An Outer Join is a join operation that selects all the rows from the first table including those match and those do not match the rows in the second table. Those not matching join condition will be a (-) value. null 2018/12/1

26 3. Left Outer Join – Syntax
SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a LEFT OUTER JOIN table2 b ; ON a.comcol = b.comcol WHERE filterCondition ORDER BY … SELECT a.comcol, a.col1, b.col2, expr1, expr2 ; FROM table1 a, table2 b ; WHERE a.comcol = b.comcol (+) and filterCondition ORDER BY … (+) sign indicates the table has missing data. 2018/12/1

27 Inner Join Outer Join No Match
eg. Make a checking list of students and the instruments they learn. The list should also contain the students without an instrument. (Outer Join) Inner Join Outer Join No Match 2018/12/1

28 eg. Make a checking list of students and the. instruments they learn
eg. Make a checking list of students and the instruments they learn. The list should also contain the students without an instrument. (Outer Join) SELECT s.class, s.name, s.id, m.type FROM stud s LEFT OUTER JOIN music m ON s.id=m.id ORDER BY 1, 2 FROM stud s, music m where s.id=m.id(+) order by 1,2 Result Outer Join empty 2018/12/1

29 Select e.employee_id, e.last_name, d.department_name
3. Outer Join Null value Select e.employee_id, e.last_name, d.department_name From employees e, departments d Where e.department_id=d.department_id(+) 2018/12/1

30 3. Outer Join (Right Outer Join)
Select e.last_name, e.department_id, d.department_name From employees e, departments d Where e.department_id (+) =d.department_id The right outer join would return all department IDs and department names even if no employees were assigned to them. 2018/12/1

31 3. Outer Join (Full Outer Join)
The results set of a full outer join includes all rows in both tables even if there is no match in the other table. Remember, in this form of an outer join, it was not possible to put a (+) on both sides of the WHERE clause. 2018/12/1

32 4. Cartesian Product / Cross Join
1. Select * from stud 2. Select * from music 3. Select * from stud, music 4. Select * from stud cross join music How many records before and after the join? 2018/12/1

33 Select worker.last_name ||' works for '|| manager.last_name
5. SELF JOIN Table : Employees Select worker.last_name ||' works for '|| manager.last_name From employees worker, employees manager Where worker.manager_id = manager.employee_id 2018/12/1

34 6. NATURAL JOIN A natural join is based on all columns in the two tables that have the same name and selects rows from the two tables that have equal values in all matched columns. It is possible to join the tables without having to explicitly specify the columns in the corresponding table. However, the names and data types in both columns must be the same. Table : d_track_listings Table : d_play_list_items SELECT event_id, song_id, cd_number FROM d_play_list_items NATURAL JOIN d_track_listings WHERE event_id = 105 2018/12/1

35 JOIN (USING Clause) 2018/12/1

36 JOIN (ON Clause) 2018/12/1

37 There are two types of subqueries:
-Single-row subqueries that use single-row operators (>, =, >=, < <>, <=) and return only one row from the inner query e.g. SELECT name from stud where mtest <= (select avg(mtest) from stud) Multiple-row subqueries that use multiple-row operators (IN, ANY, ALL) and return more than one row from the inner query 2018/12/1

38 Subqueries - IN IN (= ANY) NOT IN (<> ALL) SELECT title, year
FROM d_cds WHERE year IN (SELECT year WHERE cd_number < 94) IN (= ANY) NOT IN (<> ALL) 2018/12/1

39 Subqueries - ANY SELECT title, producer, year FROM d_cds
WHERE year = ANY (SELECT year WHERE producer = 'The Music Man') 2018/12/1

40 Subqueries - ALL SELECT title, producer,year FROM d_cds
WHERE year > ALL (SELECT year WHERE producer = 'The Music Man') 2018/12/1

41 Tutorial Exercise Time
2018/12/1

42 The End 2018/12/1

43 The union (數據庫聯合) of A and B (AB)
Lesson Review Two Tables with same structure: Table A and Table B What is Union in Multiple Tables? The union (數據庫聯合) of A and B (AB) A table containing all the rows from A and B. A B 2018/12/1

44 Real Case: Bridge Club & Chess Club
Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: Union List members of either clubs order by class, name 2018/12/1

45 The intersection (數據庫相交) of A and B (AB)
Lesson Review Two Tables with same structure: Table A and Table B What is Intersection in Multiple Tables? The intersection (數據庫相交) of A and B (AB) A table containing only rows that appear in both A and B. A B 2018/12/1

46 Real Case: Bridge Club & Chess Club
Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: Intersection Members of both clubs 2018/12/1

47 The difference (數據庫差分) of A and B (A–B)
Lesson Review Two Tables with same structure: Table A and Table B What is Difference in Multiple Tables? The difference (數據庫差分) of A and B (A–B) A table containing rows that appear in A but not in B. A B 2018/12/1

48 Real Case: Bridge Club & Chess Club
Consider the members of the Bridge Club and the Chess Club. The two database files have the same structure: Difference Members of Bridge Club but Not Chess Club 2018/12/1

49 Lesson Review 1. Union Syntax of SQL
SELECT FROM WHERE ; UNION ; SELECT FROM WHERE 2018/12/1

50 Lesson Review 2. Intersection Syntax of SQL
SELECT FROM table1 ; WHERE col IN ( SELECT col FROM table2 ) Note: col stands for one of the common column in the two tables 2018/12/1

51 Lesson Review 3. Difference Syntax of SQL SELECT ...... FROM table1 ;
WHERE col NOT IN ( SELECT col FROM table2 ) Note: col stands for one of the common column in the two tables 2018/12/1

52 This Lesson eg. 9 List the students who have not yet chosen an instrument. (No match) Student 9801 id name class Music id type No match 2018/12/1

53 WHERE id NOT IN ( SELECT id FROM music ) ;
eg. 9 List the students who have not yet chosen an instrument. No match (Difference) SELECT class, name, id FROM student ; WHERE id NOT IN ( SELECT id FROM music ) ; ORDER BY class, name Result 2018/12/1


Download ppt "Structured Query Language (II) (結構化查詢語言)"

Similar presentations


Ads by Google