选择上次报告的日期SQL

选择上次报告的日期SQL,sql,Sql,嗨,我有一张有福利温数据的表格 +---------+------------------------+-------+ |filename |Dates |LastRDt| +---------+------------------------+-------+ |Store1 |2018-01-24 12:04:45.397 | | |Stroe1 |2012-01-22 12:14:20.997 | | |Store2

嗨,我有一张有福利温数据的表格

+---------+------------------------+-------+
|filename |Dates                   |LastRDt|
+---------+------------------------+-------+
|Store1   |2018-01-24 12:04:45.397 |       |
|Stroe1   |2012-01-22 12:14:20.997 |       |
|Store2   |2013-01-24 12:20:59.407 |       |
|Store3   |2012-01-21 12:14:20.997 |       |
|Store3   |2013-01-24 12:20:59.407 |       |
+---------+------------------------+-------+
我需要创造一个句子来得到这样的东西

+---------+------------------------+--------------------------+
|Store    |Dates                   |LastRDt                   |
+---------+------------------------+--------------------------+
|Store1   |2018-01-24 12:04:45.397 |2012-01-22 12:14:20.997   |
|Stroe1   |2012-01-22 12:14:20.997 |      NULL                |
|Store2   |2013-01-24 12:20:59.407 |      NULL                |
|Store3   |2012-01-21 12:14:20.997 |      NULL                |
|Store3   |2013-01-24 12:20:59.407 |2012-01-21 12:14:20.997   |
+---------+------------------------+--------------------------+
基本上,我需要最后一次显示该值,并将该值设为lastRDt

您似乎想要上一次读取日期。您可以使用lag:


将给定文件名的最后日期存储到变量并填充LastRDt列

select filename, Dates, lastRDt
from
  (select filename, Dates, 
      IF(@lastf = filename, @lastd, NULL) as lastRDt, 
      @lastd := Dates,
      @lastf := filename
  from test, (select @lastd := NULL, @lastf := NULL) r
  order by filename, Dates) t
  order by 1,2;
select filename, Dates, lastRDt
from
  (select filename, Dates, 
      IF(@lastf = filename, @lastd, NULL) as lastRDt, 
      @lastd := Dates,
      @lastf := filename
  from test, (select @lastd := NULL, @lastf := NULL) r
  order by filename, Dates) t
  order by 1,2;