我有一个像这样的小提琴
CREATE TABLE sales(
id_order VARCHAR(50) NOT NULL,
createdAt datetime NOT NULL,
sale DECIMAL(14,2) NOT NULL,
id_location varchar(50) NOT NULL,
createdby varchar(50) NOT NULL,
order_status_id varchar(50) NOT NULL,
PRIMARY KEY(id_order,createdAt)
);
INSERT INTO sales(id_order,createdAt,sale, id_location, createdby, order_status_id)
VALUES(1,'2016-02-02',100, 1, 123, 5),
(2,'2017-03-02',150, 2, 233, 6),
(3,'2018-02-02',200, 3, 234, 6),
(4,'2016-03-03',150, 1, 123, 7),
(5,'2017-03-04',100, 2, 2334, 7),
(6,'2018-03-05',200,3, 234, 7),
(7,'2016-03-10',200, 1, 233, 7),
(8,'2017-02-01',150, 2, 124, 8),
(9,'2018-02-04',250, 3, 233, 8),
(10,'2018-02-05',300, 2, 124, 6);
CREATE TABLE location(
id_location varchar(50) NOT NULL,
location_city varchar(50) NOT NULL);
INSERT INTO location(id_location, location_city)
VALUES(1, 'Jakarta'),
(2, 'Depok'),
(3, 'Bekasi');
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=b22217bc34e3fb40c41cbaf065ca7659
然后我像这样将这种语法应用到我的真实数据库中
SELECT COALESCE(customer_regency, 'Total') AS `Kabupaten/Kota`,
SUM(quantity) AS `Qty(kg)`,
round(SUM(quantity) / any_value(totalsum) * 100, 1) AS `Qty(%)`,
COUNT(order_buyer_id) AS `Jumlah Order`,
round(COUNT(order_buyer_id) / any_value(totalcount) * 100, 1) AS `Jumlah Order(%)`
FROM order_match
/* 1 */ INNER JOIN air_way_bills
/* 1 */ ON order_match.code_order = air_way_bills.code_order
/* 2 */ INNER JOIN ( SELECT s1.createdby
FROM order_match s1
WHERE s1.order_status_Id in (4, 5, 6, 8)
GROUP BY s1.createdby
HAVING SUM(s1.createdAt BETWEEN '2020-01-02' AND '2020-02-03')
AND SUM(s1.createdAt <= '2020-02-03') > 1 ) clients
/* 2 */ ON order_match.createdby = clients.createdby
JOIN ( SELECT SUM(quantity) totalsum,
COUNT(order_buyer_id) totalcount
FROM order_match
/* 3 */ INNER JOIN ( SELECT s2.createdby
FROM order_match s2
WHERE s2.order_status_id in (4, 5, 6, 8)
GROUP BY s2.createdby
HAVING SUM(s2.createdAt BETWEEN '2020-01-02' AND '2020-02-03')
AND SUM(s2.createdAt <= '2020-02-03') > 1 ) clients
/* 3 */ ON order_match.createdby = clients.createdby
WHERE order_status_Id in (4, 5, 6, 8)) totals
WHERE order_status_Id in (4, 5, 6, 8)
GROUP BY customer_regency WITH ROLLUP;
我在我的真实数据库中有点困惑,为什么总百分比的输出计数为 99,6 %(如果我们谈论TOTAL ,它应该是 100% )