为数据库中的每个债务人/客户选择max(datediff())

zu0ti5jz  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(274)

出于研究目的,我有以下问题(针对单个债务人):

SELECT MAX(DATEDIFF(r.next_created, r.created))
    FROM (

    # finds each created and the next consecutive one in the table
    SELECT r1.created as created, (

        # finds the next consecutive created
        SELECT created
        FROM (db) r2
        WHERE r2.created > r1.created
        ORDER BY created ASC
        LIMIT 1
    ) as next_created

    FROM (db) r1
    ORDER BY r1.created) as r

但是,我非常希望能够将其扩展到我数据库中的每一个id。你们有什么意见吗,关于我怎么做?
提前谢谢。

6kkfgxo0

6kkfgxo01#

SELECT r.debtor, MAX(DATEDIFF(r.next_created, r.created))
FROM (SELECT r1.*
             (SELECT r2.created
              FROM db r2
              WHERE r2.debtor = r1.debtor AND r2.created > r1.created
              ORDER BY r2.created ASC
              LIMIT 1
             ) as next_created
      FROM db r1
     ) r
GROUP BY r.debtor;

这假设您的表有一个名为 debtor (或某事)表明你关心什么。

相关问题