选择上次报告的日期SQL

时间:2018-01-25 00:30:07

标签: sql

您好我有一张包含folliwin数据的表

+---------+------------------------+-------+
|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

2 个答案:

答案 0 :(得分:1)

您似乎想要之前的阅读日期。您可以使用lag()

select t.*,
       lag(dates) over (partition by store order by dates) as prev_dates
from t;

答案 1 :(得分:0)

将给定文件名的最后日期存储到变量并填充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;