确定具有相同ID的上一条记录的时间跨度

时间:2019-04-16 07:38:50

标签: mysql mysql-5.6

我有一张桌子,它在不同的日期多次出现相同的动物ID。

tableA
+-----------+------------+
| animalid  |  calvdate  |
+-----------+------------+
| A         | 2018-08-30 |
| B         | 2018-08-30 |
| A         | 2018-09-10 |
| C         | 2018-08-30 |
| A         | 2019-08-30 |
+-----------+------------+

我想创建一个表来计算自上次记录动物以来的天数

expected output
+-----------+------------+--------------+
|  animalid |  calvdate  | NumberOfDays |
+-----------+------------+--------------+
| A         | 2018-08-30 |            0 |
| A         | 2018-09-10 |           11 |
| A         | 2019-08-30 |          355 |
| B         | 2018-08-30 |            0 |
| C         | 2018-08-30 |            0 |
+-----------+------------+--------------+

我尝试使用以下查询:

SELECT
  animalid,
  calvdate, TO_DAYS(x.calvdate)-TO_DAYS(calvdate) AS NumberOfDays, 
  (SELECT calvdate FROM tableA as x WHERE animalid = animalid ORDER BY asc)
FROM
  tableA 

如何生成预期的输出?

2 个答案:

答案 0 :(得分:1)

此查询将为您提供所需的结果。它LEFT JOIN将原始表置为自身,其中第二个表中的calvdate小于第一个表中的最大calvdate。然后,我们使用这两个日期的差来获取时间长度,使用COALESCE处理第二个表中没有匹配的行:

SELECT a.animalid, a.calvdate, 
       COALESCE(TIMESTAMPDIFF(DAY, b.calvdate, a.calvdate), 0) AS NumberOfDays
FROM tableA a
LEFT JOIN tableA b ON b.animalid = a.animalid AND
                      b.calvdate = (SELECT MAX(calvdate) 
                                    FROM tableA a2 
                                    WHERE a2.calvdate < a.calvdate 
                                      AND a2.animalid = a.animalid)
ORDER BY a.animalid

输出:

animalid    calvdate    NumberOfDays
A           2018-08-30  0
A           2018-09-10  11
A           2019-08-30  354
B           2018-08-30  0
C           2018-08-30  0

Demo on dbfiddle

答案 1 :(得分:1)

您可以使用以下查询:

SELECT tableA.animalid,tableA.calvdate,TO_DAYS(tableA.calvdate)-TO_DAYS(x.calvdate) AS NumberOfDays 
    FROM tableA 
    inner join (
        SELECT MIN(calvdate), animalid FROM tableA GROUP BY animalid)
    ) x ON tableA.animalid = x.animalid

它用于获取联接中子查询中所有动物的最短日期,并将其用于减法以查找NumberOfDays字段。