2012-08-29 72 views
1

參照這個問題選擇與分組

select all the rows until date diff is 4 from bottom

解決方案中的所有行,直到日期的差異條件匹配的偉大工程,而是如何通過CUSTOMER_ID和第4天差異各CUSTOMER_ID組,第8天和DIFF組

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

+0

通過一些示例數據,您能夠顯示預期的結果集嗎? – eggyal

+0

這裏是預期圖表http://sqlfiddle.com/#!2/2f207/2 –

+1

如果你只是在這裏使用正確的代碼格式粘貼SQL,因爲必須訪問外部鏈接往往是令人沮喪,尤其是更好只有少數幾行實際代碼。 – tadman

回答

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