I have the data structure as below:
Schema (MySQL v5.7)
CREATE TABLE customers(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20),
PRIMARY KEY (id)
);
INSERT INTO customers (name) VALUES
('Wayne Enterprises'),
('Star Labs'),
('Daily Planet');
CREATE TABLE orders(
id INT NOT NULL AUTO_INCREMENT,
customer_id INT,
order_date DATE,
order_amount DECIMAL(13,2),
ship_by VARCHAR(20),
PRIMARY KEY (id),
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
INSERT INTO orders(customer_id, order_date, order_amount, ship_by) VALUES
(1, '2018-11-14', 100.00, "Robin"),
(2, '2018-11-15', 200.00, "The Flash"),
(3, '2018-11-15', 150.00, "The Flash"),
(1, '2018-11-21', 110.00, "The Flash"),
(2, '2018-11-22', 175.00, "The Flash"),
(2, '2018-11-22', 175.00, "Cyborg");
I use this query to number the order, counted for each customer because the MySQL 5.7 doesn't have some useful functions like RANK, ROW_NUMBER :(
Order numbering
SELECT
c.id as cus_id,
c.name as customer_name,
o.id as o_id,
@order_number:=IF(@current_customer = o.customer_id,
@order_number + 1,
1) AS order_number,
o.order_date,
o.order_amount,
o.ship_by,
@current_customer:=o.customer_id AS current_customer
FROM
orders o LEFT JOIN customers c ON c.id = o.customer_id
,(select @current_customer:=null, @order_number:=0) vars
ORDER BY o.customer_id, o.order_date, o.id;
| cus_id | customer_name | o_id | order_date | order_amount | ship_by | order_number | current_customer |
|---|---|---|---|---|---|---|---|
| 1 | Wayne Enterprises | 1 | 2018-11-14 | 100.00 | Robin | 1 | 1 |
| 1 | Wayne Enterprises | 4 | 2018-11-21 | 110.00 | The Flash | 2 | 1 |
| 2 | Star Labs | 2 | 2018-11-15 | 200.00 | The Flash | 1 | 2 |
| 2 | Star Labs | 5 | 2018-11-22 | 175.00 | The Flash | 2 | 2 |
| 2 | Star Labs | 6 | 2018-11-22 | 175.00 | Cyborg | 3 | 2 |
| 3 | Daily Planet | 3 | 2018-11-15 | 150.00 | The Flash | 1 | 3 |
Now I am looking for a way to select all customers with their highest order_number that shipped by "The Flash". The expected query result, which corresponds to the above example data:
| cus_id | customer_name | o_id | o_num |
|---|---|---|---|
| 1 | Wayne Enterprises | 4 | 2 |
| 2 | Star Labs | 5 | 2 |
| 3 | Daily Planet | 3 | 1 |
I tried and ended with sub-query problems which stop me for a couple of days already. Could anyone help?