SQL knowledge for WebSAMS
2010
Schedule
DAT module
Basic SQL knowledge ( 30 mins )
Learning Query by Examples (40 mins)
Break (15 mins)
Joining tables (40 mins)
Exercise ( 40 mins )
Optional Part
More SQL examples
Tools for Sybase database
Interactive SQL
Sybase Central
2
Training material download
All PowerPoint, exercises and suggested answers
can be downloaded at :
http://cdr.websams.edb.gov.hk/
Training material download (contd)
http://www.hkedcity.net/teachernet/sharing/forum/index.phtml?forum_id=52 5
DAT Module
Data Mgmt > Query Maintenance
DAT Module (cont'd)
Data Mgmt > Report
Basic SQL knowledge for WebSAMS
Target audience:
School WebSAMS users who are not familiar with SQL.
What is SQL?
SQL stands for Structured Query Language.
SQL allows you to access a RDBMS (Relational
Database Management System)
It presents data as a collection of rows and
columns
SQL has three major parts :
DDL Data Definition Language
DML Data Manipulation Language
DCL Data Control Language
9
SQL Scope
DDL:
i) Create, change and delete
database object (e.g. tables,
indexes, views)
ii) Command Keywords:
CREATE, DROP,ALTER
Only select is
allowed in
WebSAMS!
iii) SQL example:
DML:
i) Syntax for executing
queries
ii) e.g. SELECT , INSERT ,
UPDATE, DELETE
CREATE TABLE class (class_no
INTEGER, stud_name
CHAR(40))
DCL:
Control access right
iii) SQL Example:
select * from
TB_STU_STUDENT
e.g. GRANT
10
Terms of Relational Database
Tables
Fields
Records
Keys
Views
Indexes
11
Tables
A database contains many tables
table is a set of data elements (values) that is
organized using a model of horizontal rows and
vertical columns.
The logical order of records and fields within a
table is of absolutely no important.
Example:
TB_STU_STUDENT
VW_STU_LATESTSTUDENT
12
Fields
A field is the smallest structure in the database.
Fields are the structures that are actually used to
store data.
Field name not case sensitive
13
Records
A record represents a unique instance of the
subject of a table.
It is composed of the entire set of fields in a
table, regardless of whether or not the fields
contain any values.
Fields (columns)
Table:
Records
(rows)
*School *Schyear *Class *Class no Student
ID
name
Sex
1293
2006
1A
John
1293
2006
1B
Mary
1293
2006
1C
Ken
.
14
Keys
A key field is a field of a database table which together
form a unique identifier for a database record.
The aggregate of these fields is usually referred to
simply as "the key".
Example:
door key > locate a house
schyear,class,classno > locate a student
Primary key: A Primary Key is a field (or a group of fields ) that can
be used to identify a unique row in a table.
Foreign key: A Foreign Key in one table refers to the primary key
of another table.
For example, I write an email to introduce a book to you, with ISBN of the
book (not the entire text of the book). The ISBN is the primary-key of the
book, and it is used as a foreign-key in the e-mail.
15
Indexes
An index is a feature in a database that allows quick
access to the rows in a table.
The index is created using one or more columns of the
table.
The index is optimized for quick searching
Example:
If a magazine (without table of content) is a table,
the table of content is a kind of index
The 'magazine' contains fields of page no, subject titles, contents
The 'table of contents' contains fields of page no and subject titles
16
Table and Index
Fields
Table:
(columns)
*School *Schyear *Class *Class
ID
no
Student
name
Sex
Records 1293
2006
1A
John
(rows)
1293
2006
1B
Mary
1293
2006
1C
Ken
SQL :
create index .
*School
ID
*Schyear
*Class
*Class
no
1293
2006
1A
1293
2006
1B
1293
* = Keys
2006
1C
Index:
17
Example: (table in WebSAMS)
Table: TB_STU_STUDENT
Keys: SUID, STUID
18
Example: (table in WebSAMS)
Table: TB_SCH_SCHCLASS
Keys: SUID, SCHYEAR, SCHLEVEL, SCHSESSION, CLASSCODE
19
Related Information
Table Structure
Field description
Data type
Key
Index
You can get a report of table structure for
difference modules from DAT module.
20
Table Structure
Information in the report
Table
Field of Record
Name & Description (Comment)
Name, Description (Comment), Data Type, Mandatory,
Primary Key & Foreign Key
Index
Name & Column list
21
Data Types
Character Data Types
Numeric Data Types
INTEGER, UNSIGNED INT(n), SMALLINT,
DECIMAL(n,p), NUMERIC(n,p)
FLOAT, DOUBLE
Date & Time Data Types
CHAR(n), VARCHAR(n), LONG VARCHAR
DATE, TIMESTAMP
Other Data Types
BIT(n), LONG BINARY
22
Mandatory
If a field is not mandatory, then the field value
can be NULL a missing or unknown value.
NULL does not represent a zero, a character
string of one or more blank spaces, or a
"zero-length" character string.
23
Unknown Values: NULL
A NULL in a column means that the user or
application has made no entry in that column. A
data value for the column is undefined .
NULL does not mean the same as zero (numerical
values) or blank (character values). Rather, NULL
values allow you to distinguish between a deliberate
entry of zero for numeric columns or blank for
character columns and a non-entry, which is NULL
for both numeric and character columns.
24
Learning Query By Example
The SELECT statement
25
SELECT statement
SELECT column_list
FROM table_list
[WHERE search_condition]
[GROUP BY column_list]
constrains
[HAVING search_condition]
[ORDER BY {column_list | column_index}]
Keys:
[ ] - optional
{ } - list of parameters
| - or
Notice:
The result set usually becomes smaller in size
when no. of constrains increase
26
Simplest Query
SELECT column_list FROM table_list
27
Sample Queries
SELECT * FROM TB_STU_Student
* stands for all fields in the table
select enname, chname
from TB_STU_STUDENT
select distinct classcode
from TB_STU_STUDENT
select enname + ' (' + chname + ')'
from TB_STU_STUDENT
28
Sample Queries
select
enname as 'English Name',
chname 'Chinese Name',
enname + ' (' + chname + ')' Student
from TB_STU_STUDENT
Syntax:
Column-name AS alias
Column-name alias
29
Table alias
select
a.enname AS 'English Name',
a.chname 'Chinese Name',
a.enname + ' (' + a.chname + ')' Student
from TB_STU_STUDENT a
30
ORDER BY clause
select distinct classcode
from TB_STU_STUDENT
order by classcode
select classcode, classno, enname, chname
from TB_STU_STUDENT
order by classcode desc, classno asc
select classcode, classno, enname, chname
from TB_STU_STUDENT
order by 1 desc, 2 asc
31
Exercise 1 (order by)
Use table TB_STU_STUDENT ,
find student class, classno, name
Sort the result set by class and class no.
Hints: How to check the field name? Go to Data Mgmt > Report
Suggested answers:
select classcode, classno, enname, chname
from TB_STU_STUDENT
order by classcode, classno
32
WHERE clause with one expression
[WHERE search_condition]
fields
select
Table (or table list)
from
where
An expression
which return true or
false
order by
fields
33
Sample Queries
select classcode, classno, enname, chname
from TB_STU_STUDENT
where classlvl ='S1'
order by classcode, classno
34
Search Condition for WHERE
Comparison (=, <, >, <=, >=, <>)
Range
Membership
[NOT] IN (value list)
Pattern Match
[NOT] BETWEEN start_value AND end_value
[NOT] LIKE pattern_string
Wildcard characters : % _
NULL
IS [NOT] NULL
35
Sample Queries
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE ClassCode BETWEEN '4' AND '5Z'
ORDER BY ClassCode, EnName
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE ClassLvl IN (S4', S5')
ORDER BY ClassCode, EnName
36
Sample Queries
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE EnName LIKE 'CHAN %'
ORDER BY EnName
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE HKID IS NULL
ORDER BY ClassCode, EnName
37
Simple logic for where condition
select .
select .
from .
from .
where condition1 or condition2
where condition1 and condition2
T or T = True
T and T = True
F or F = False
F and F = False
T or F = True
T and F = False
F or T = True
F and T = False
38
WHERE clause with two or more
expression
Reminder: each expression will only returns true or false.
where
where
or
or
or
where
39
WHERE clause with two or more
expression (contd)
where
where
and
or
or
where
40
WHERE clause with two or more
expression (contd)
where
where
and (
or
and
where
41
Sample Queries
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
True or False?
WHERE
ClassLvl IN (S4', S5')
AND
True or False?
EnName LIKE 'CHAN %'
ORDER BY ClassCode, EnName
42
Sample Queries
SELECT ClassCode, ClassNo, EnName, ChName,
STRN, HKID
FROM TB_STU_Student
True or False?
WHERE
( HKID IS NULL OR STRN IS NULL )
True or False?
AND
ClassCode BETWEEN '1' AND '2Z'
True or False?
ORDER BY ClassCode, ClassNo
43
Useful Functions (Date)
YEAR(date_field)
MONTH(date_field)
DAY(date_field)
NOW()
getDate()
DateFormat(date_field, date_format)
E.g. select dateformat( date_field, 'DD/MM/YYYY') from .
44
Sample Queries
SELECT
DOB,
YEAR(DOB),
MONTH(DOB),
DAY(DOB),
NOW(),
DATEFORMAT(DOB, 'DD/MM-YYYY')
FROM TB_STU_Student
Notice:
A field can be selected more than once,
depends on the data set you need
45
Useful Functions (String)
UPPER(text_field)
LOWER(text_field)
TRIM(text_field)
LEFT(text_field, length)
RIGHT(text_field, length)
SUBSTRING(text_field, start position, length)
LENGTH(text_field)
46
Sample Queries
SELECT
EnName,
LOWER(EnName),
TRIM(EnName),
SUBSTRING(EnName, 3, 5),
LENGTH(EnName)
FROM TB_STU_Student
47
Exercise 2 ( substring )
Find out the classcode, class no. , student name, first 6 digits of strn
of each student, order by class and class no., and format the student
name as , e.g. Chan Tai Man ()
Hints: How to check the field name? Go to Data Mgmt > Report
Use function: substring(text_field, start position, length)
Syntax: text_field + ( + text_field2 + )
Suggested Answer:
select classcode, classno, enname +' ('+chname+')' ,
substring( strn, 2, 6 ) 'first 6 digits'
from TB_STU_STUDENT
order by classcode, classno
48
Exercise 3 ( where )
Also display the date of birth field, with format DD/MM/YYYY
Filter the students with birth year 1999,
and the class code of the student should not be empty.
Hints:
Use function: dateformat( date_field, 'DD/MM/YYYY')
Year(field_name)
Suggested answers:
select classcode, classno, enname +' ('+chname+')' , substring(
strn, 2, 6 ) 'first 6 digits' , dateformat( dob, 'DD/MM/YYYY')
from TB_STU_STUDENT
where YEAR(dob) = ? and classcode <> ''
order by classcode, classno
49
Aggregate Functions
COUNT([DISTINCT] field)
SUM([DISTINCT] field)
AVG([DISTINCT] field)
MAX(field)
MIN(field)
50
GROUP BY clause
[GROUP BY column_list]
When you use aggregate functions in the
SELECT clause to produce summary
information, you use the GROUP BY clause
to divide the information into distinct groups.
The GROUP BY clause is optional.
51
What is Count function?
select ClassCode ,EnName
from TB_STU_Student
ClassCode
EnName
1A
Mary
1A
John
1A
Ken
1B
David
1B
Peter
1C
Calvin
select ClassCode , COUNT(EnName) ClassCode
1A
from TB_STU_Student
1B
group by ClassCode
1C
Count(EnNam)
3
2
1
52
Sample Queries 1
This SQL find out the number of student in each class:
select
ClassCode 'Class',
COUNT(EnName) 'No. of Student'
from TB_STU_Student
group by ClassCode
order by ClassCode
Think: a SQL has count(..) but no 'group by'
e.g. select count(*) from TB_STU_STUDENT
53
Sample Queries 2
This SQL find out the number of student in Form 1,
group by class and gender:
SELECT
ClassCode 'Class', Sex, COUNT(*) 'No. of Student'
FROM TB_STU_Student
WHERE ClassCode in ('1A','1B','1C','1D','1E')
GROUP BY ClassCode, Sex
ORDER BY ClassCode, Sex
54
Sample Query 3
The table TB_STU_STUSCHREC stores all the schooling record of each
student in each year.
select stuid,
MIN( firstattdate ) 'First Attend Date'
from TB_STU_STUSCHREC
group by stuid
stuid
firstattdate
Class
0001
1-9-2006
1A
0002
1-9-2005
1A
0002
31-9-2006
1B
0003
1-9-2004
2E
0003
12-9-2005
2E
0003
1-9-2006
2B
0004
1-9-2004
2B
0004
1-9-2005
2B
0005
1-9-2006
5A
0006
1-9-2006
5B
55
Exercise 4 (function )
1)
Use table TB_STU_STUDENT, find how many student in the
class 1A, 2B 3C and 4D respectively.
Hint: use the function count(field_name)
use fields classcode and enname
Suggested answers:
select classcode, count( enname )
from TB_STU_STUDENT
where classcode in ( '1A', '2B' , '3C' , '4D' )
group by classcode
order by classcode
2) Use table TB_STU_STUSCHREC, find the first attend date of each
student.
Hint: use function min(field_name), and fields stuid, firstattdate
Suggested answers:
select stuid, min(firstattdate) 'First Attend Date'
from TB_STU_STUSCHREC
group by stuid
56
HAVING clause
[HAVING search_condition]
The HAVING clause is specifically associated with
the GROUP BY clause, and you use it to filter the
grouped information.
*It is similar to the WHERE clause in that the
HAVING keyword is followed by an expression that
evaluates to TRUE, FALSE or UNKNOWN.
HAVING is also an optional clause.
57
Sample Queries 1
SELECT
ClassCode 'Class',
COUNT(EnName) 'No. of Student'
FROM TB_STU_Student
WHERE ClassCode <> ''
GROUP BY ClassCode
HAVING COUNT(EnName) > 40
ORDER BY ClassCode
Note:
1) HAVING is needed only when GROUP BY exists.
2) This is a wrong syntax:
where COUNT(EnName) > 40
58
Exercise 5 ( having )
1) Continue Ex.4.1, find out the class with more than 40 students
within the class 1A, 2B and 3C and 4D :
Suggested answers:
select classcode, count( enname ) from TB_STU_STUDENT
where classcode in ( '1A', '2B' , '3C' , '4D' )
group by classcode
having count( enname ) > 40
order by classcode
2) Continue Ex.4.2, find out the student who join the school after
2006-09-02:
Hint: First find the minimum First Attend Date for each stuid, then use having
for filtering
Use function: datetime( YYYY-MM-DD )
Suggested answers:
select stuid, min(firstattdate) 'First Attend Date'
from TB_STU_STUSCHREC
group by stuid
having min(firstattdate) > datetime('2006-09-02')
59
Useful Syntax
CASE
WHEN condition1
THEN result1
WHEN condition2
THEN result3
....
ELSE
result
END
60
Sample Queries
SELECT
ClassCode, ClassNo, AreaCode,
CASE
WHEN AreaCode = 1 THEN Hong Kong'
WHEN AreaCode = 2 THEN Kowloon'
WHEN AreaCode = 3 THEN N.T.'
ELSE 'N/A'
END 'AREA'
FROM TB_STU_Student
ORDER BY ClassCode DESC, ClassNo
61
Exercise 6.1 ( case when )
From subject assessment table (TB_ASR_SUBJASSESSDATA),
Find student id (stuid), subjcode (subjcode), and score (sysscore).
SYNTAX:
For code 071, display chemistry,
CASE
WHEN . THEN .
WHEN . THEN .
ELSE .
END
for code 085, display chinese, others display Others
School year and time sequence should be 2006 and 1100 respectively.
Modify this SQL:
Suggested answers:
select
stuid,
subjcode,
subjcode Subject Name,
sysscore
from TB_ASR_SUBJASSESSDATA
where schyear=2006
and timeseq=1100
select stuid, subjcode,
case
when subjcode='071' then 'chemistry'
when subjcode='085' then 'chinese'
else 'Others'
end 'Subj name'
,sysscore
from TB_ASR_SUBJASSESSDATA
where schyear=2006 and timeseq=1100
62
Exercise 6.2 ( case when ) DEMO
From parent table (TB_STU_PARENT),
find the name of parents, and the relation value.
For the relation value, display mother for 01 , father for 02, other
for other values.
Suggested Answer:
select enname, chname,
case
when relation='01' then 'mother'
when relation='02' then 'father'
else 'other'
end 'relation'
from TB_STU_PARENT
63
Revision:
SELECT column_list
FROM table_list
[WHERE search_condition]
[GROUP BY column_list]
constrains
[HAVING search_condition]
[ORDER BY {column_list | column_index}]
Keys:
[ ] - optional
{ } - list of parameters
| - or
64
Writing Practical Query for
WebSAMS
65
Advanced query syntax
Join table
Sub-query
Left outer join, inner join
Field and search condition
Combining query
66
Join Table
Inner join
Left Outer join
67
Join Table
TB_NAME
*stuid
name
001
Ken
002
May
003
John
*stuid
classcode classno
001
4A
18
002
2E
004
1C
26
TB_CLASS
68
Inner Join
An Inner Join returns only those rows where
the linking values(keys) match in both of the
tables or in Result Sets
Example:
Table alias: refer the field to table a and b
select a.stuid , a.name, b.classcode, b.classno
from TB_NAME a
join TB_CLASS b
on a.stuid = b.stuid
69
Example of Inner Join
Alternative version:
select a.stuid, a.firstname, b.classcode, b.classno
from TB_NAME a, TB_CLASS b
where a.stuid=b.stuid
Result:
a.stuid
a.name
b.classcode b.classno
001
Ken
4A
18
002
May
2E
70
Exercise 7.1 ( inner join)
70
Table: VW_STU_LATESTSTUDENT and TB_ASR_STUDASSESSDATA by
using inner join.
suid
stuid
suid
schyear
stuid
schyear
syspercscore
a.suid=b.suid
a.stuid=b.stuid
a.schyear=b.schyear
?
Inner join
Result set
classlevel
classcode
classno
Student
name
syspercscore
71
Exercise 7.1 contd ( inner join)
2007Term 170
Table:
VW_STU_LATESTSTUDENT and
TB_ASR_STUDASSESSDATA by using inner join.
Suggested answer:
Select
a.classlvl, a.classcode, a.classno, a.chname,b.syspercscore 'average'
from VW_STU_LATESTSTUDENT a
join TB_ASR_STUDASSESSDATA b
on a.suid = b.suid and a.STUID = b.STUID
and a.schyear = b.schyear
where b.schyear = ? and b.TIMESEQ = ? and b.syspercscore >= 70
order by a.classlvl,a.classcode, a.classno
TIMESEQ -- 1000 (), 1100 (T1), 1201 (T2A1), 1302 (T3A2)
SYSPERCSCORE --
72
Code Table Mapping
Common code table
Most frequently used: TB_HSE_COMMON
Independent code table
Class Level (TB_HSE_ClsLvl)
Qualification (TB_HSE_QualCD)
Subject Component (TB_HSE_SbjCmp)
Training Course (TB_HSE_TrnCD)
73
Code Table Mapping TB_ID
74
Use code table, find subject name
Step 1) Subject Assessment Table:
1st term score in 2006:
select schyear, suid, stuid, subjcode,
sysscore
from TB_ASR_SUBJASSESSDATA
where schyear=2006 and timeseq=1100
TB_ID = SBJ
Step 2) Code table:
select suid, tb_id, code_id, en_des
from TB_HSE_COMMON
where tb_id = 'SBJ'
75
a.suid
TB_ASR_SUBJASSESSDATA (a) b.tb_id
a.subjcode
b.suid
TB_HSE_COMMON (b)
SBJ
b.code_id
suid
tb_id
Code_id
Description
9999
RELATE
01
Mother
9999
RELATE
02
Father
suid
subjcode
score
9999
076
33
9999
SBJ
076
History
9999
085
45
9999
SBJ
085
Chinese
9999
9999
ECACD
1010
Drama Club
INNER JOIN
(values match both table)
Result set
a.suid
a.Stuid
a.subjcode
b.description
a.score
9999
250
076
History
33
9999
394
085
Chinese
45
76
Contd
Step 3) Combine the SQLs by inner join:
select a.schyear, a.suid, a.stuid, a.subjcode, b.en_des, a.sysscore
from TB_ASR_SUBJASSESSDATA a
join TB_HSE_COMMON b
on a.suid=b.suid and b.tb_id='SBJ' and a.subjcode = b.code_id
where a.schyear=2006 and a.timeseq=1100
77
Exercise 7.2 (common code table)
Exercise: Find the parent name and translate the relation code
of each parent by the common code table:
Step 1) Parent table:
SELECT suid, relation, enname 'Parent
Name', Relation 'Code'
FROM TB_STU_Parent
ORDER BY EnName
Step 2) Code table:
select suid, tb_id, code_id, en_des
from TB_HSE_COMMON
where tb_id = 'RELATE'
78
Exercise 7.2 (contd)
Suggested Answer:
SELECT a.EnName 'Parent Name',
a.Relation 'Code', b.En_Des 'Relation'
FROM TB_STU_Parent a
JOIN TB_HSE_Common b
on b.SUID = a.SUID
and b.Tb_ID = 'RELATE'
and b.Code_ID = a.Relation
order by a.EnName
79
Left Outer Join
A left outer join is very different from an inner join. Instead of limiting
results to those in both tables, it limits results to those in the "left" table (A).
This means that if the ON clause matches 0 records in B, a row in the result
will still be returnedbut with NULL values for each column from B.
It returns all the values from left table + only matched values from
right table.
80
Left Outer Join (Example)
select a.stuid , a.name, b.classcode, b.classno
from TB_NAME a
left outer join TB_CLASS b
on a.stuid = b.stuid
TB_CLASS
001
4A
18
002
2E
004
1C
26
TB_NAME
TB_CLASS
001
Ken
001
4A
18
002
May
002
2E
003
John
004
1C
26
TB_CLASS
Result :
001
4A
18
002
2E
004
1C
26
a.stuid
a.name
b.classcode
b.classno
001
Ken
4A
18
002
May
2E
003
John
(NULL)
(NULL)
Left outer join: left table as master table , and join the right table
81
Sample Queries
Getting the parent name of each student:
This returns the name of each student, whenever he/she has a parent
record or not
select
a.EnName 'Student Name',
b.EnName 'Parent Name'
from TB_STU_Student a
left outer join TB_STU_Parent b
on
a.StuID = b.StuID and
a.SUID = b.SUID
ORDER BY a.EnName
82
Example (Left outer join)
Get Student and Parent Name,
order by class and class no.
from tables TB_STU_Student and TB_STU_Parent
TB_STU_Student
TB_STU_Parent
LEFT OUTER JOIN
83
Example
Get Student and Parent Name,
Order by class and class no.:
SUID
SELECT
a.ClassCode 'Class Code',
a.ClassNo 'Class No',
a.EnName 'Student Name,
b.EnName Parent Name
FROM TB_STU_Student a
LEFT OUTER JOIN
TB_STU_Parent b
ON
b.StuID = a.StuID and
b.SUID = a.SUID
WHERE
a.ClassCode <> ''
ORDER BY a.ClassCode, a.ClassNo
STUID
SUID
STUID
Parent
LEFT OUTER JOIN
Class
code
Class
No
Stud
Name
Parent Name
1A
Peter
Mr. Wong
1A
John
(NULL)
1B
Mary
Mr. Chang
1B
Tim
Mr. Lee
1B
Joe
(NULL)
1C
Jack
Mr. Yan
1C
Henry
Mr. Lau
1C
Eric
Mr. Kwan
84
Exercise 8.1 (left outer join)
2006, Term1
Table:
VW_STU_LATESTSTUDENT and
TB_ASR_SUBJASSESSDATA
Use left outer join join.
VW_STU_LatestStudent
Left outer
join
TB_ASR_SUBJASSESSDATA
85
Exercise 8.1 (contd)
Suggested answer:
select
a.schyear , a.classlvl , a.classcode ,
b.sysscore , b.OMclasslvl
a.classno ,
a.chname ,
from VW_STU_LATESTSTUDENT a
left outer join TB_ASR_SUBJASSESSDATA b
on a.suid = b.suid and a.stuid = b.stuid and a.schyear = b.schyear and
b.subjcode='080' and b.timeseq = 1100
where a.schyear = 2007 and a.classlvl = 'S1'
order by a.classcode, a.classno
86
Exercise 8.2
2007Term1
Hints: subject code = 165
Suggested answer:
select
a.schyear , a.classlvl , a.classcode , a.classno ,
b.sysscore 'chi subj score', b.OMclasslvl 'chi OM',
c.sysscore 'eng subj score', c.OMclasslvl 'eng OM'
a.chname ,
from VW_STU_LATESTSTUDENT a
left outer join TB_ASR_SUBJASSESSDATA b
on a.suid = b.suid and a.stuid = b.stuid and a.schyear = b.schyear and
b.subjcode='080' and b.timeseq = 1100
left outer join TB_ASR_SUBJASSESSDATA c
on a.suid = c.suid and a.stuid = c.stuid and a.schyear = c.schyear and
c.subjcode='165' and c.timeseq = 1100
where a.schyear = 2007 and a.classlvl = 'S1'
order by a.classcode, a.classno
87
Advanced Topics
88
Sub-Query
A subquery is an SQL SELECT statement
that's nested inside of another SQL
statement
A subquery can appear in the field list (as in
the preceding example) or in a WHERE or
HAVING clause
89
SUID
STUID
SUID
STUID
Required Query
Parent
LEFT OUTER JOIN
Student without parent record:
Class
code
Class
No
Stud
Name
Parent Name
SELECT
a.ClassCode 'Class Code',
a.ClassNo 'Class No',
a.EnName 'Student Name'
FROM TB_STU_Student a
LEFT OUTER JOIN TB_STU_Parent b
ON
b.StuID = a.StuID and
b.SUID = a.SUID
WHERE
a.ClassCode <> '' AND
b.EnName IS NULL
ORDER BY a.ClassCode, a.ClassNo
1A
Peter
Mr. Wong
1A
John
(NULL)
1B
Mary
Mr. Chang
1B
Tim
Mr. Lee
1B
Joe
(NULL)
1C
Jack
Mr. Yan
1C
Henry
Mr. Lau
1C
Eric
Mr. Kwan
WHERE
Class
code
Class
No
Stud
Name
Parent Name
1A
John
(NULL)
1B
Joe
(NULL)
90
Transformed to
Sub-Query
STUID
Class
code
Class
No
Stud
Name
001
1A
Peter
002
1A
John
003
1B
Mary
004
1B
Tim
005
1B
Joe
Student without parent record:
SELECT
006
1C
1
Jack
a.STUID ,
a.ClassCode 'Class Code',
STUID Parent Name
a.ClassNo 'Class No',
a.EnName 'Student Name'
001
Mr. Wong
WHERE
FROM TB_STU_Student a
003
Mr. Chang
where
004
Mr. Lee
006
Mr. Yan
a.classcode <> '' and
a.stuid not in
(select stuid from tb_stu_parent) STUID Class
Class
Stud
STUID
NOT
IN
ORDER BY a.ClassCode,
code
No
Name
a.ClassNo
002
1A
2
John
005
1B
Joe
91
Evaluation Order
Evaluation Order
Type of Operator
Positive Sign (+), Negative Sign (-)
Multiplication (*), Division (/)
Addition (+), Subtraction (-)
=, <, >, <=, >=, <>,
BETWEEN, IN, LIKE, IS NULL
NOT
AND
OR
92
Advanced Example Calculate Age
SELECT ClassCode, EnName, dob,
case
when (MONTH(dob) > MONTH(NOW()))
then YEAR(NOW())-YEAR(dob)-1
when ((MONTH(dob) = MONTH(NOW()))
and (DAY(dob) > DAY(NOW())))
then YEAR(NOW())-YEAR(dob)-1
else YEAR(NOW())-YEAR(dob)
end 'AGE'
FROM TB_STU_Student
WHERE ClassCode <> ''
ORDER BY ClassCode, EnName
93
Harder Example Age Statistics
SELECT ClassLvl,
YEAR(NOW())-YEAR(DOB)-(CASE
WHEN (MONTH(DOB)*40+DAY(DOB) >
MONTH(NOW()) *40+DAY(NOW()))
THEN 1
ELSE 0
END) 'AGE',
COUNT(EnName) 'No. of Student'
FROM TB_STU_Student
WHERE ClassCode <> ''
GROUP BY ClassLvl, AGE
ORDER BY ClassLvl, AGE
94
Harder Example Full Address
SELECT ClassCode, ClassNo, EnName,
(CASE WHEN TRIM( EnFlatNo )<>''
THEN 'Flat '+TRIM( EnFlatNo )+', ' ELSE '' END)
+ (CASE WHEN TRIM(EnFloorNo)<>''
THEN 'Floor '+TRIM(EnFloorNo)+', ' ELSE '' END)
+ (CASE WHEN TRIM(EnBlkNo)<>''
THEN 'Block '+TRIM(EnBlkNo)+', ' ELSE '' END)
+ (CASE WHEN TRIM(EnBuilding)<>''
THEN TRIM(EnBuilding)+', ' ELSE '' END)
+ (CASE WHEN TRIM(EnVillageEstate)<>''
THEN TRIM(EnVillageEstate)+', ' ELSE '' END)
95
+ (CASE WHEN TRIM(EnStreet)<>''
THEN TRIM(EnStreet)+', ' ELSE '' END)
+ (CASE WHEN TRIM(EnDistrict)<>''
THEN TRIM(EnDistrict)+', ' ELSE '' END)
+ (CASE WHEN AreaCode=1 THEN 'Hong Kong'
WHEN AreaCode=2 THEN 'Kowloon'
WHEN AreaCode=3 THEN 'New Territories'
ELSE '' END) AS Address
FROM TB_STU_Student
ORDER BY EnName
96
Query Repository
Student
Assessment
Staff
97
More SQL samples Student
Student information
Student information with parent
Student information with user-defined fields
Student information with last year's class
code
S5 & S7 graduated student list
98
More SQL samples Assessment
Examination score
Examination score with component
Top 20 students of a subject
English subject component score
Score of Chinese subject with component
List of student that fail Chinese, English or
Mathematics
99
More SQL samples Staff
Class teacher list
Staff information for ESDA
Staff information with qualification
100
Interactive SQL software
An interactive program for executing SQL
statement
The program is bundled in the Sybase
database system and is installed on the
WebSAMS server already
101
Interactive SQL software
Play DEMO
Points to note :
Connect the database with valid account
genuser, stfuser or fmpuser
Add wsadmin. before each table name
(inconvenient ?)
By default, only the first 500 records will be
retrieved
102
Sybase Central
The program is a tool for managing database
The program is bundled in the Sybase
database system and is installed on the
WebSAMS server already
103
Sybase Central
Play DEMO
Points to note :
Connect the database with valid account
genuser, stfuser or fmpuser
104
End of Workshop
105