You are on page 1of 2

SELECT s.staff_id, count( DISTINCT i.

film_id ) as total
FROM staff as s
join rental as r on r.staff_id = s.staff_id
JOIN inventory as i ON r.inventory_id = i.inventory_id
where year(r.rental_date) = 2005
GROUP BY s.staff_id;

select c.customer_id , sum(p.amount) as payment


from customer as c
join payment as p on p.customer_id = c.customer_id
group by c.customer_id;

DELIMITER //
CREATE FUNCTION totalPayByCustomer(c_id INT)
RETURNS decimal(10,2)
READS SQL DATA
BEGIN
DECLARE t INT;
select sum(p.amount) into t
from customer as c
join payment as p on p.customer_id = c.customer_id
where c.customer_id = c_id;
RETURN t;
END
//
DELIMITER ;

drop trigger if exists after_insert_payment;


DELIMITER //
CREATE TRIGGER after_insert_payment AFTER INSERT ON payment
FOR EACH ROW
BEGIN
DECLARE temp DECIMAL(10,2);
SET temp = totalPayByCustomer(new.customer_id);

IF(new.customer_id not IN (SELECT customer_id from customer_rank)) THEN


if (temp > 150) then insert into customer_rank values (new.customer_id,
'Platinum');

elseif (temp > 100) then insert into customer_rank values


(new.customer_id, 'Gold');

elseif (temp > 50) then insert into customer_rank values (new.customer_id,
'Silver');
end if;
ELSE
if (temp > 150) then update customer_rank set rank = 'Platinum' where
customer_id = new.customer_id;
elseif (temp > 100) then update customer_rank set rank = 'Gold' where
customer_id = new.customer_id;
end if;
END IF;
END
//
DELIMITER ;

drop trigger if exists after_update_payment;


DELIMITER //
CREATE TRIGGER after_update_payment AFTER UPDATE ON payment
FOR EACH ROW
BEGIN
DECLARE temp DECIMAL(10,2);
SET temp = totalPayByCustomer(new.customer_id);

IF(new.customer_id not IN (SELECT customer_id from customer_rank)) THEN


if (temp > 150) then insert into customer_rank(customer_id, rank)
values (new.customer_id, 'Platinum');
elseif (temp > 100) then insert into customer_rank(customer_id, rank)
values (new.customer_id, 'Gold');
elseif (temp > 50) then insert into customer_rank(customer_id, rank) values
(new.customer_id, 'Silver');
end if;
ELSE
if (temp > 150) then update customer_rank set rank = 'Platinum' where
customer_id = new.customer_id;
elseif (temp > 100) then update customer_rank set rank = 'Gold' where
customer_id = new.customer_id;
end if;
END IF;
END
//
DELIMITER ;

insert into payment(customer_id, staff_id, rental_id, amount) values (4,1,1,20);

2 1 3 4

You might also like