根据最近三个订单计算每个客户的退货率

时间:2020-08-17 12:07:44

标签: mysql sql

DB-Fiddle

CREATE TABLE sales (
    id int auto_increment primary key,
    customerID VARCHAR(255),
    order_date DATE,
    sales_volume INT,
    returned_volume INT
);

INSERT INTO sales
(customerID, order_date, sales_volume, returned_volume
)
VALUES 
("Customer_01", "2020-01-01", "200", "50"),
("Customer_01", "2020-02-15", "400", "120"),
("Customer_01", "2020-02-21", "300", "0"),
("Customer_01", "2020-03-17", "800", "480"),
("Customer_01", "2020-04-08", "600", "315"),
("Customer_02", "2020-02-02", "500", "175"),
("Customer_02", "2020-02-03", "900", "620"),
("Customer_02", "2020-03-27", "100", "30"),
("Customer_02", "2020-04-15", "375", "120"),
("Customer_03", "2020-08-12", "700", "280"),
("Customer_04", "2020-03-09", "260", "110");

预期结果:

customerID      return_rate_last_3_orders
Customer_01             46.76                     = (315+480+0) / (600+800+300)
Customer_02             56.00                     = (120+30+620) / (375+100+900)
Customer_03             40.00                     = (280) / (700)
Customer_04             42.31                     = (110) / (260)

在上表中,我每个orderscustomer及其对应的sales_volumereturn_volume

现在,我要计算每个客户最近3个订单退货率

到目前为止,我想到了以下查询:

SELECT
customerID,
SUM(sales_volume),
SUM(returned_volume),
(SUM(returned_volume) / SUM(sales_volume)) AS return_rate
FROM sales
GROUP BY 1
LIMIT 3;

但是我不知道如何将limit应用于每个return_rate的{​​{1}}的计算。
我该如何修改customer才能获得预期的结果?

1 个答案:

答案 0 :(得分:0)

如果我理解正确,则可以使用AddressCode来枚举行,然后在进行汇总之前进行过滤:

ROW_NUMBER()

Here是db <>小提琴。