GROUP BY Flashcards
SELECT customer_id, SUM(amount) FROM payment
GROUP BY customer_id
ORDER BY SUM(amount) DESC;
Answers the questions of how much each customer is spending and puts them in descending order by total spent
SELECT customer_id, SUM(amount), COUNT(rental_id) FROM payment
GROUP BY customer_id
ORDER BY SUM(amount) DESC;
similiar to previous query, amount spent by customer but also provides # of transactions per customer
SELECT DATE(payment_date), SUM(amount) FROM payment
GROUP BY DATE(payment_date)
ORDER BY DATE(payment_date);
Provides a list of total sales by day in descending order of day. One note is the DATE function takes a timestamp column and extracts just the day of the month and drops the time
SELECT customer_id, SUM(amount) FROM payment
GROUP BY customer_id
ORDER BY SUM(amount) DESC
LIMIT 5;
Gives the top 5 customer ids per amount spent
SELECT ROUND(AVG(replacement_cost),2), rating FROM film GROUP BY rating;
provides an average replacement cost based off of rating of film
SELECT staff_id, COUNT(payment_id) FROM payment
GROUP BY staff_id
ORDER BY COUNT(payment_id) DESC;
used to determine which Staff ID has performed the greatest # of transactions
HAVING clause
allows a filtering to take place AFTER an aggregation has taken place. HAVING is generally a WHERE statement but only used for GROUP BY
SELECT SUM(amount), customer_id FROM payment GROUP BY customer_id HAVING SUM(amount) > 100;
List of customer ids who have spent more than $100. Need to use HAVING instead of WHERE because filtering based off of an aggregate function
SELECT COUNT(customer_id), store_id FROM customer GROUP BY store_id HAVING COUNT(customer_id) > 300;
providing a list of store_ids with more than 300 customers
SELECT customer_id, COUNT(payment_id) FROM payment
GROUP BY customer_id
HAVING COUNT(payment_id) >= 40;
creates a list of customers that have had more than 40 transactions
SELECT customer_id, SUM(amount) FROM payment
WHERE staff_id = 2
GROUP BY customer_id
HAVING SUM(amount) > 100;
Provides customer_id and sum of amount spent with staff_id number 2. Where statement comes before the having and is not part of aggregate function
SELECT customer_id, SUM(amount) FROM payment
WHERE staff_id = 2
GROUP BY customer_id
HAVING SUM(amount) >= 110;
provides a list of customers spending more than 110, where purchased were made with staff_id number 2