2017-04-06 34 views
1

Coulmns表現:添加列查詢與前行的列值輸出在MySQL

id   toDate          
-----  ----------  
111   02-03-2017            

111   20-03-2017             

111   01-04-2017  

111   05-04-2017    

Coulmns在查詢將返回:

id   toDate   fromDate       
-----  ----------  ---------- 
111   02-03-2017  01-01-01 <---(always first record value) 

111   20-03-2017  02-03-2017 <---(rest of the rows should be previous record's toDate value)        

111   01-04-2017  20-03-2017 

111   DatedNow   01-04-2017 <-- last record toDate should be current date 

我有以下查詢 查詢select id,toDate from myHistory order by toDate;

需要添加查詢以獲得所需輸出的查詢是什麼?

+0

在數據庫中沒有 「上一行」。直到您使用 – Jens

回答

3

你可以用這樣的查詢做到這一點:

SELECT id,toDate,fromDate 
FROM (
    SELECT m.*, @fromDate AS fromDate 
    ,@fromDate := m.toDate 
    FROM myHistory m 
    CROSS JOIN (SELECT @fromDate:='1901-01-01') AS init 
    ORDER BY toDate 
) AS result; 

樣品

mysql> SELECT id,toDate,fromDate 
    -> FROM (
    ->  SELECT m.*, @fromDate AS fromDate 
    ->  ,@fromDate := m.toDate 
    ->  FROM myHistory m 
    ->  CROSS JOIN (SELECT @fromDate:='1901-01-01') AS init 
    ->  ORDER BY toDate 
    ->) AS result; 
+-----+------------+------------+ 
| id | toDate  | fromDate | 
+-----+------------+------------+ 
| 111 | 2017-03-02 | 1901-01-01 | 
| 111 | 2017-03-20 | 2017-03-02 | 
| 111 | 2017-04-01 | 2017-03-20 | 
+-----+------------+------------+ 
3 rows in set (0,00 sec) 

mysql> 
+0

訂購嗨Bernd Buffen,您可以編輯您的答案,因爲我編輯了該問題。道歉不要在開始時添加DatedNow值。謝謝。 –