4. Grouping Data
Last updated
Last updated
(divide rows into groups and applies an aggregate function on each)
It divides the rows returned from SELECT
statement into groups
For each group, we can apply an aggregate function
PostgreSQL evaluates this clause something like this
In this case, it works like DISTINCT
clause that removes duplicate rows from the result set
To select the total amount that each customer has been paid, you use the GROUP BY clause to divide the rows in the payment table into groups grouped by customer id
The following statement uses the GROUP BY clause with the INNER JOIN clause the get the total amount paid by each customer. Unlike the previous example, this query joins the payment table with the customer table and group customers by their names.
To find the number of payment transactions that each staff has processed, we can
To group the payment by dates, we can use DATE()
function to convert timestamps
(apply conditions to groups)
It specifies a search condition for a group or an aggregate
It is often used with GROUP BY
clause to filter groups or aggregates
Its evaluation sequence is
Since, it is evaluated before SELECT
clause, we cannot use column aliases in HAVING clause
WHERE
allows us to filter rows based on a specified condition
HAVING
allows us to filter groups of rows according to specified condition
To find total amount of each customer who have been spending more than 200
To select a store that has more than 300 customers