在Mysql中显示一行中的上一个和下一个日期值

时间:2018-04-20 03:44:59

标签: mysql sql

我有一个这样的表,我正在使用MySQL并且仍然坚持在之前的记录中显示日期。

intDateId |  dateLeave  | dateCreated | intUpdateOrder
1         |  2018-04-01 | 2018-04-01  |  NULL
2         |  2018-04-02 | 2018-04-01  |  NULL
3         |  2018-04-11 | 2018-04-02  |  1
4         |  2018-04-20 | 2018-04-02  |  2

到目前为止,这是我的查询,我仍然无法显示上一个日期:

    SELECT 
     intDateId, 
     GROUP_CONCAT(dateLeave) AS datePrevious, // i'm stuck here
     GROUP_CONCAT(dateLeave) AS dateCurrentUpdate, 
     intUpdateOrder
    FROM leave_date
    WHERE intUpdateOrder IS NOT NULL
    GROUP BY intUpdateOrder

我想要的是这样的:

dateCreated | datePrevious             | dateCurrentUpdate   | intUpdateOrder
2018-04-02  | (2018-04-01, 2018-4-02)  | (2018-04-11)        | 1 // datePrevious WHERE intUpdateOrder NULL
2018-04-02  | (2018-04-11)             | (2018-04-20)        | 2 // datePrevious WHERE intUpdateOrder 1

谢谢

1 个答案:

答案 0 :(得分:2)

尝试以下查询

SELECT
  q1.dateCreated,
  q2.datePrevious,
  q1.dateCurrentUpdate,
  q1.intUpdateOrder
FROM
  (
    SELECT
      t.*, 
      @rownum1 := @rownum1 + 1 AS rank
    FROM
      (
        SELECT
          IFNULL(intUpdateOrder,0) intUpdateOrder,
          MAX(dateLeave) dateCurrentUpdate,
          MAX(dateCreated) dateCreated
        FROM leave_date
        GROUP BY intUpdateOrder
      ) t,
      (SELECT @rownum1 := 0) r
    ORDER BY intUpdateOrder
  ) q1
JOIN
  (
    SELECT
      t.*, 
      @rownum2 := @rownum2 + 1 AS rank
    FROM
      (
        SELECT
          IFNULL(intUpdateOrder,0) intUpdateOrder,
          GROUP_CONCAT(dateLeave) datePrevious
        FROM leave_date
        GROUP BY intUpdateOrder
      ) t,
      (SELECT @rownum2 := 0) r
    ORDER BY intUpdateOrder
  ) q2
ON q1.rank=q2.rank+1

SQL小提琴 - http://www.sqlfiddle.com/#!9/006e88/17