MySQL has no window function support, but you can use a correlated subqueries in the SELECT
list to retrieve exactly one column:
SELECT
event_id,
event_type,
event_time,
(SELECT COUNT(*) FROM events EC WHERE EC.event_type = E.event_type AND EC.event_time > E.event_time) AS subsequent_event_count
FROM
events E
WHERE ...
Do EXPLAIN
it. This is kinda the same in terms of execution logic as the CROSS APPLY
in SQL Server.
Another approach is a self join:
SELECT
E.event_id,
E.event_type,
E.event_time,
COUNT(EC.event_id) AS subsequent_event_count
FROM
events E
LEFT JOIN events EC
ON E.event_type = EC.event_type AND E.event_type < EC.event_type
GROUP BY
E.event_id,
E.event_type,
E.event_time
Do test both approaches for performance.
You can do much more creative joins, like
EC.event_time > E.event_time AND EC.event_time < E.event_time + INTERVAL 1 DAY
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…