This document discusses SQL grouping, aggregation, filtering and views. It provides examples of using GROUP BY to group and count data, HAVING to filter aggregated results, and views to encapsulate queries as virtual tables. Exercises demonstrate using these SQL features to group and filter sales data, count enrolled students by course, and create a view for high credit courses.
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
26 views
Database Systems Lab 6 Presentation
This document discusses SQL grouping, aggregation, filtering and views. It provides examples of using GROUP BY to group and count data, HAVING to filter aggregated results, and views to encapsulate queries as virtual tables. Exercises demonstrate using these SQL features to group and filter sales data, count enrolled students by course, and create a view for high credit courses.
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12
LAB 6: SQL GROUP BY,
HAVING AND VIEWS
• Objective: Delve into SQL's aggregation mechanisms and the creation of views. Understand the importance of grouping and filtering aggregated data and encapsulating complex queries as views. SQL GROUP BY CLAUSE • The GROUP BY statement groups rows that have the same values in specified columns into aggregate data, like COUNT, SUM, AVG, etc. EXAMPLE: SQL GROUP BY • SELECT CourseName, COUNT(StudentID) AS NumberOfStudents FROM Enrollment GROUP BY CourseName; EXERCISE: SQL GROUP BY • Group the 'Sales' table by 'Product' and count the number of sales for each product. SQL HAVING CLAUSE • The HAVING clause lets you filter result sets based on a condition applied to the aggregated data. It is often used with GROUP BY. EXAMPLE: SQL HAVING • SELECT CourseName, COUNT(StudentID) AS NumberOfStudents FROM Enrollment GROUP BY CourseName HAVING COUNT(StudentID) > 10; EXERCISE: SQL HAVING • From the 'Sales' table, list products that have been sold more than 50 times. SQL VIEWS • A view is a virtual table based on the result-set of an SQL statement. It contains rows and columns, just like a real table. However, the fields in a view are fields from one or more real tables in the database. EXAMPLE: SQL VIEWS • CREATE VIEW View_StudentsAbove18 AS SELECT StudentName, Age FROM Students WHERE Age > 18; EXERCISE: SQL VIEWS • Create a view named 'HighCreditCourses' that lists courses from the 'Courses' table with credits more than 4. ADVANCED SQL GROUPING AND VIEWS • Using GROUP BY and HAVING clauses, we can aggregate data and filter it based on conditions. Views allow for encapsulation of SQL queries and can simplify complex data retrieval tasks. FEEDBACK AND QUESTIONS • Students are encouraged to provide feedback and ask questions at the end of the lab.