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)
在上表中,我每个orders
有customer
及其对应的sales_volume
和return_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
才能获得预期的结果?