有3个表 - 折扣(折扣)客户(客户)和订单(订单)
折扣
------------------------------------------------
|id_discount | count_orders | percent_discount |
------------------------------------------------
| 1 | 5 | 1,5 |
| 2 | 10 | 2,5 |
客户
------------------------------------------------
| id_client | Name | Surname |
------------------------------------------------
| 1 | Ivan | Petrov |
| 2 | Vasya | Vasev |
订单
------------------------------------------------
| id | order_sum | id_client |
------------------------------------------------
在给定客户订单数量的情况下,如何计算总金额的问题?如果订单总数为5及以上,则折扣为1.5%,如果为10及以上,则为2.5%。否则,没有折扣。提前致谢
答案 0 :(得分:0)
为了使其正常工作,您还需要为0个订单打折。
插入Discount(count_orders,percent_discount)值(0,0);
要查找具有给定ID的客户的折扣百分比,请执行以下操作:
select d.percent_discount
from Discount d
where d.count_orders = isnull(
(select max(count_orders)
from Discount dI where count_orders <= (
select count(1) from Orders oI where oI.id_client = 1)), 0)
获取每个客户的折扣:
select c.id_client as client_id,
(select d.percent_discount
from Discount d
where d.count_orders = isnull(
(select max(count_orders)
from Discount dI where count_orders <= (
select count(1) from Orders oI where oI.id_client = c.id_client)), 0)) as discount
from Clients c
结合使用选项查找每个订单的折扣价格:
select o.id,
c.name,
c.surname,
o.order_sum,
(o.order_sum - (o.order_sum * client_discount.discount / 100)) as sumWithDiscount
from Orders o join Clients c on o.id_client = c.id_client
join (select cI.id_client,
(select d.percent_discount
from Discount d
where d.count_orders = isnull(
(select max(count_orders)
from Discount dI where count_orders <= (
select count(1) from Orders oI where oI.id_client = cI.id_client)), 0)) as discount
from Clients cI) as client_discount on client_discount.id_client = c.id_client
答案 1 :(得分:-1)
DELIMITER $$
CREATE PROCEDURE `getDiscount`(IN _orderSum INT(11))
BEGIN
DECLARE countOrders INT(11) DEFAULT 0;
DECLARE percentDiscount DOUBLE DEFAULT 0;
DECLARE done INT(1);
DECLARE cur CURSOR FOR SELECT count_orders, percent_discount FROM Discount ORDER BY count_orders DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET done = 0;
OPEN cur;
discountLoop: LOOP
FETCH cur INTO countOrders, percentDiscount;
IF done = 1 THEN LEAVE discountLoop; END IF;
IF _orderSum >= countOrders THEN
SELECT percentDiscount AS percent_discount FROM dual;
SET done = 1;
END IF;
END LOOP discountLoop;
CLOSE cur;
END$$
DELIMITER ;