Ejemplos agregados

select first_name, last_name, sum(amount) total ,
 count(amount) numero , avg(amount) media,
 max(amount) maximo , min(amount) minimo
from customer join payment using (customer_id)
group by customer_id
order by numero desc
limit 5 
-- limit solo un número: devuelve las primeras n filas dos numeros: a partir del primer número n filas
-- limit 10: los 10 primeros. limit 10,10 a partir de la fila 10, 10 registros

select first_name, last_name, sum(amount) total ,
 count(amount) numero , avg(amount) media,
 max(amount) maximo , min(amount) minimo
from customer join payment using (customer_id)
where first_name like 'M%' -- Antes de calcular el total
group by customer_id
having total>150 -- Cuando ya se han calculado los totales

-- ¿Cuál es el país con menos ciudades?

select country, count(city_id) total 
from country join city using(country_id)
group by country_id
order by total asc
limit 1;

select country, count(customer_id) total from customer join address using(address_id)
join city using(city_id)
join country using(country_id)
group by country_id
order by total desc

-- Películas y categorías

select * from category join film_category using(category_id)
join film using (film_id);

-- Añado agrupación

select name,count(film_id) from category join film_category using(category_id)
join film using (film_id)
group by category_id;

-- Añado restricción sobre los campos
-- ¿Cuantas películas de cada categoría tienen rating 'G'

select name,count(film_id) total from category join film_category using(category_id)
join film using (film_id)
where rating='G'
group by category_id;

-- Añado restricción sobre el total
-- ¿Cuantas categorías tienen más de 10 películas con rating 'G'?

select name,count(film_id) total from category join film_category using(category_id)
join film using (film_id)
where rating='G'
group by category_id
having total>10

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos