By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE orders
(`id` int, `customer` int, `order_type` varchar(9), `amount` int, `created_dt` date)
;
INSERT INTO orders
(`id`, `customer`, `order_type`, `amount`, `created_dt`)
VALUES
(1, 1, 'web', 5, '2017-01-01'),
(2, 1, 'web', 7, '2017-01-05'),
(3, 2, 'web', 2, '2017-01-07'),
(4, 3, 'web', 2, '2017-02-01'),
(5, 3, 'web', 3, '2017-02-01'),
(6, 2, 'web', 5, '2017-03-15'),
(7, 1, 'in_person', 7, '2017-02-01'),
(8, 3, 'web', 8, '2017-01-01'),
(9, 2, 'web', 1, '2017-04-01')
;
SELECT YEAR(created_dt) year, MONTH(created_dt) month, COUNT(*) second_orders
FROM (
SELECT created_dt,
@rn := IF(@c = customer, @rn + 1, 1) rn,
@c := customer
FROM orders CROSS JOIN (
SELECT @c := NULL, @rn := 1
) i
WHERE order_type = 'web'
ORDER BY customer, id
) q
WHERE rn = 2
GROUP BY YEAR(created_dt), MONTH(created_dt)
ORDER BY year, month
year | month | second_orders |
---|---|---|
2017 | 1 | 1 |
2017 | 2 | 1 |
2017 | 3 | 1 |