将当前行值与php中的下一行值进行比较

时间:2018-05-16 04:30:15

标签: php mysql

SizeToContent="Width"

如何比较第一行到期日期和第二行付款日期。我需要显示像Diff(ID UserID Payment_Date Expired_Date Diff(Payment_Date&Expired_Date) 1 123 2017-08-01 00:00:00 2018-01-01 00:00:00 2 123 2018-02-01 00:00:00 2018-10-01 00:00:00 31 3 123 2018-10-05 00:00:00 2018-10-10 00:00:00 4 & Payment_Date)31,4。

这样的结果

1 个答案:

答案 0 :(得分:0)

不需要PHP,您可以在SQL中执行此操作

SELECT ID, UserID, Payment_Date, Expired_Date, lastpayement, DATEDIFF(lastpayement, Expired_Date) AS DIFF
FROM
(
    SELECT m.ID, m.UserID, m.Payment_Date, m.Expired_Date, 
            (
                SELECT Payment_Date
                FROM mytable tt
                WHERE  m.Expired_Date < tt.Payment_Date AND tt.UserID=m.UserID
                GROUP BY UserID
            ) AS lastpayement
    FROM mytable m
) t 

结果

| ID | UserID |         Payment_Date |         Expired_Date |         lastpayement |   DIFF |
|----|--------|----------------------|----------------------|----------------------|--------|
|  1 |    123 | 2017-08-01T00:00:00Z | 2018-01-01T00:00:00Z | 2018-02-01T00:00:00Z |     31 |
|  2 |    123 | 2018-02-01T00:00:00Z | 2018-10-01T00:00:00Z | 2018-10-05T00:00:00Z |      4 |
|  3 |    123 | 2018-10-05T00:00:00Z | 2018-10-10T00:00:00Z |               (null) | (null) |

SQLfiddle