Gunakan variabel untuk memperbaiki rentang sebelum mengagregasi total
SELECT t.`fk_id`,
@rn := if(@id = `fk_id`,
@rn + 1,
if(@id:=`fk_id`, if(@end:='1900-01-01 00:00:00',1,1), if(@end:='1900-01-01 00:00:00',1,1))
) as rn,
if(start < @end,
@end,
if(@end := end, `start`, `start`)
) as `start`,
end
FROM Table1 t
CROSS JOIN (SELECT @id := 0, @end := STR_TO_DATE('1900-01-01 00:00:00', '%Y-%m-%d %H:%i:%s') as e, @rn := 0) t
ORDER BY `fk_id`, `start`
KELUARAN