sql—在一行中显示mysql中的上一个和下一个日期值

kq0g1dla  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(317)

我有一个这样的表,我正在使用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

谢谢您

zqdjd7g9

zqdjd7g91#

尝试以下查询

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号

相关问题