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沒有LEAD
或LAG
功能。我如何在單個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
不顯示正確在所有情況下的最後一列。
任何想法?