如何在同一列中的两个日期之间获得日期?

时间:2015-09-07 08:26:36

标签: mysql

我有表格结构,如Loanid是外键

TranID  LOANID       TRANSDATE  
2          2          2013-05-01     
13         2          2013-05-10     
14         2          2013-05-15    
6          5          2013-05-01   
7          5          2013-06-10     
8          5          2013-06-14   
9          5          2013-07-01    
10         5          2013-07-10   

我需要一个查询来计算下面的天数。

TranID  LOANID       TRANSDATE    DAYS_BETWEEN
2          2          2013-05-01    9 
13         2          2013-05-10    5 
14         2          2013-05-15    0
6          5          2013-05-01   41
7          5          2013-06-10    4 
8          5          2013-06-14   17
9          5          2013-07-01    9
10         5          2013-07-10    0

1 个答案:

答案 0 :(得分:1)

可能是自我加入,使用MIN来获得下一个日期。

SELECT t1.tranid, 
        t1.loanid, 
        t1.transdate
        DATEDIFF(IFNULL(MIN(t2.transdate), t1.transdate),  t1.transdate) AS days
FROM some_table t1
LEFT OUTER JOIN some_table t2
ON t1.loanid = t2.loan_id
AND t1.transdate < t2.transdate
GROUP BY t1.tranid, 
        t1.loanid, 
        t1.transdate