Professional Documents
Culture Documents
Part 4 - Grouping Data and Subqueries
Part 4 - Grouping Data and Subqueries
Part 4 - Grouping Data and Subqueries
Data
Le Duy Dung (Andrew)
SQL – Part 3
SQL Expressions and Functions
Grouping
❑ Grouping is a tool for dividing data into sets
❑ We can perform aggregate calculations on the resulted sets
❑ Groups are created using GROUP BY clause
Group By
❑ Example: Group the vendors by their cities and return the total
number of Vendors in each city
• To calculate the number of vendors in one specific city we have:
SELECT COUNT(*) AS NumberOfVendors
FROM VENDORS
WHERE City = ‘Seattle’;
❑ The reason WHERE does not work here because filtering is based on
the aggregated value, not the value of the rows
❑ In other words, WHERE filters before data is grouped; HAVING
filters after data is grouped.
Group By and Having
❑ Example: Find all customers who bought more than $1000 at the
store.
SELECT CustomerID, SUM(Total) as TotalBought
FROM SALE
GROUP BY CustomerID
Having SUM(Total) > 1000;
Subqueries
❑ A subquery is query embedded into other query
❑ Let’s consider an example:
❑ We want to recognize the best performing salesperson among the
employee.
❑ We need to know the total sale of each employee
❑ Get the employee with the highest sale.
Subqueries
We want to recognize the best performing salesperson among
the employee.
SELECT Top 1 EmployeeID, TotalSale
FROM (SELECT EmployeeID, SUM(Total) AS TotalSale
FROM SALE
GROUP BY EmployeeID)
ORDER BY TotalSale DESC;