Lec9 Lab CSC371 Database Systems
Lec9 Lab CSC371 Database Systems
(Lab)
(Spring2020)
Abdul Qayyum [email protected]
Samia Arshad [email protected]
Faisal Mumtaz [email protected]
1
Previous Lecture Review
SQL Update
SQL Delete
SQL Select Top
SQL ORDER BY
SQL Aliases
SQL MIN() and MAX() Functions
SQL COUNT(), AVG() and SUM() Functions
2
Branch
Staff
3
Agenda
SQL Group By Clause
SQL Having Clause
SQL Views
4
GROUP BY Syntax
Groups rows that have the same values into summary rows
Find the number of staff members in each branch
It is often used with aggregate functions to group the result-set by one
or more columns.
Used COUNT, MAX, MIN, SUM, AVG functions.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
5
Show branch wise data from staff table?
Select * from staff group by branchno
Select * from staff order by branchno
6
Use of Group by with Count function
Count how many employees in each branch?
7
Group By with ORDER BY Clause
10
The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.
Applied condition on group data
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
11
Can we find out the branch number with more than two
employees
12
select branchNo, count(staffno) As [Total Employee], Avg(salary) AS [Average
Salary]
From staff
Where salary >= 9000
Group by branchno
Having count(staffno) > 1
Order By count(staffno) DESC;
13
select branchNo, count(staffno) As [Total Employee], Avg(salary) AS [Average
Salary]
From staff
Where salary > 10000
Group by branchno
Having count(staffno) > 1;
14
SQL CREATE VIEW Statement
15
SQL CREATE VIEW
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
CREATE VIEW [Branch_B003] AS
SELECT staffno, fname, salary
FROM staff
WHERE branchno = ‘B003’’;
16
SQL CREATE OR REPLACE VIEW
17
Drop View
DROP VIEW [branch_b003];
18
Summary
19