1

关于这个问题

选择所有行,直到日期差异从底部开始为 4

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

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

4

1 回答 1

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

于 2012-08-29T06:25:44.997 回答