选择所有行,直到日期差异条件与分组匹配

时间:2012-08-29 05:32:47

标签: mysql

参考这个问题

select all the rows until date diff is 4 from bottom

解决方案效果很好但如何按customer_id和每个customer_id组进行分组4天差异,8天差异

http://sqlfiddle.com/#!2/93d75/3

1 个答案:

答案 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上查看。