2015-07-21 65 views
0

假設我有以下數據:MySQL的後柱DATEDIFF

CUSTOMER_ID CONTACT_ID COMM_CREATION_DAY DAYS_SINCE_LAST_CONTACT 
10000  28036173295 2014-12-21  0 
10000  28365672745 2015-01-29  DATEDIFF('2015-01-29','2014-12-21') 
10000  28576719155 2015-02-26  DATEDIFF('2015-02-26','2014-01-29') 
38409  28432217395 2015-02-07  0 
38409  28565986955 2015-02-25  DATEDIFF('2015-02-25,'2015-02-07') 

我試圖讓DAYS_SINCE_LAST_CONTACT列,但有在MySQL沒有LEADLAG功能。我如何在單個SELECT聲明中執行此操作?

我試過如下:

SELECT CUSTOMER_ID, COMM_ID , COMM_CREATION_DAY, PREVIOUS_COMM_CREATION_DAY FROM 
(
select 
c.* 
, @prev AS PREVIOUS_COMM_CREATION_DAY 
, @prev := COMM_CREATION_DAY 
FROM contacts c, (select @prev:=NULL) vars 
ORDER BY CUSTOMER_ID, c.COMM_CREATION_DAY, c.COMM_ID 
) sq 
ORDER BY CUSTOMER_ID, COMM_CREATION_DAY 

但是,這給了我:

CUSTOMER_ID CONTACT_ID COMM_CREATION_DAY LAST_CONTACT_DATE 
10000  28036173295 2014-12-21  NULL 
10000  28365672745 2015-01-29  2014-12-21 
10000  28576719155 2015-02-26  2015-01-29 
38409  28432217395 2015-02-07  2015-02-26 (THIS IS INCORRECT!) 
38409  28565986955 2015-02-25  2015-02-07 

哪裏NULL不顯示正確在所有情況下的最後一列。

任何想法?

回答

0

是在MySQL中,你需要使用用戶定義的變量對這些計算的東西如

select 
customer_id, 
contact_id, 
contact_date, 
DAYS_SINCE_LAST_CONTACT 
from(
    select 
    customer_id, 
    contact_id, 
    contact_date, 
    @diff:= if(@prev_customer = customer_id,datediff(contact_date,@prev_date),0) as DAYS_SINCE_LAST_CONTACT, 
    @prev_customer:=customer_id, 
    @prev_date:= contact_date 
    from customer c,(select @prev_customer:=0,@prev_date:=null)x 
    order by customer_id,contact_date 
)x 

http://sqlfiddle.com/#!9/6cb9f/2