参考这个问题
select all the rows until date diff is 4 from bottom
解决方案效果很好但如何按customer_id和每个customer_id组进行分组4天差异,8天差异
答案 0 :(得分:1)
您只需要跟踪最新的customer_id
并执行“播放”逻辑:
SELECT amount, customer_id, updated_at, date_diff
FROM (
SELECT *,
@b:=NOT @c<=>customer_id
OR (@b AND DATEDIFF(@t,updated_at)<=date_diff) AS okay,
@c:=customer_id,
@t:=updated_at
FROM my_table, (SELECT 4 AS date_diff) init
ORDER BY customer_id, updated_at DESC
) t
WHERE okay
ORDER BY customer_id, updated_at, id
在sqlfiddle上查看。