Day 3 - Course Slides
Day 3 - Course Slides
Aggregation functions
SUM
Aggregation functions
AVG
Most common
aggregation functions
SUM()
AVG()
MIN()
MAX()
COUNT()
SYNTAX
SELECT
SUM(amount)
FROM payment
SYNTAX
SELECT
COUNT(*)
FROM payment
What we can't do…
SELECT
SUM(amount)
payment_id
FROM payment
No mixing possible!
SELECT
SUM(amount)
Only possible with
payment_id grouping!
FROM payment
Multiple aggregations is possible!
SELECT
SUM(amount),
COUNT(*),
AVG(amount)
FROM payment
Your manager wants to which of the two employees (staff_id)
is responsible for more payments?
Result
Solution
SELECT
MIN(replacement_cost),
MAX(replacement_cost),
ROUND(AVG(replacement_cost),2) AS AVG,
SUM(replacement_cost)
FROM film
GROUP BY
SUM
SYNTAX
SELECT
customer_id,
SUM(amount)
FROM payment
GROUP BY customer_id
SYNTAX
SELECT
customer_id,
SUM(amount)
FROM payment
WHERE customer_id >3
GROUP BY customer_id
SYNTAX
SELECT
customer_id,
SUM(amount)
FROM payment
WHERE customer_id >3
GROUP BY customer_id
ORDER BY customer_id
SYNTAX
SELECT
customer_id, Every column:
In GROUP BY or
SUM(amount) in aggregate functions
FROM payment
GROUP BY customer_id
SYNTAX
SELECT
customer_id, Every column:
In GROUP BY or
SUM(amount) in aggregate functions
FROM payment
GROUP BY customer_id
There are two competitions between the two employees.
Result
Your manager wants to get a better understanding of the
films.
That's why you are asked to write a query to see the
• Minimum
• Maximum
• Average (rounded)
• Sum
of the replacement cost of the films.
Write a SQL query to get the answers!
Result
HAVING
HAVING
COUNT(*)>400
Note!
HAVING an only be used
with GROUP BY!
SYNTAX
SELECT
customer_id,
SUM(amount)
FROM payment
GROUP BY customer_id
HAVING SUM(amount)>200
Solution
SELECT
MIN(replacement_cost),
MAX(replacement_cost),
ROUND(AVG(replacement_cost),2) AS AVG,
SUM(replacement_cost)
FROM film
In 2020, April 28, 29 and 30 were days with very high revenue.
That's why we want to focus in this task only on these days
(filter accordingly).
Find out what is the average payment amount grouped by
customer and day – consider only the days/customers with
more than 1 payment (per customer and day).
Order by the average amount in a descending order.
Result