我有一张这样的表:
Id FKId Amount1 Amount2 Date
-----------------------------------------------------
1 1 100,0000 33,0000 2018-01-18 19:57:39.403
2 2 50,0000 10,0000 2018-01-19 19:57:57.097
3 1 130,0000 40,0000 2018-01-20 19:58:13.660
5 2 44,0000 2,0000 2018-01-21 11:11:00.000
如何从3 - 5(所有日期为2018-01-21或2018-01-21)获取行,还有关于FKId(1和2)的前一行?
谢谢
答案 0 :(得分:1)
在大多数数据库中,您可以使用ANSI标准lead()
函数:
select t.*
from (select t.*, lead(date) over (partition by fkid order by date) as next_date
from t
) t
where date in ('2018-01-20', '2018-01-21') or
next_date in ('2018-01-20', '2018-01-21');
或者,如果您只想要所有日期大于某个日期和前一条记录的记录,则此逻辑也有效:
select t.*
from t
where t.date >= (select max(t2.date)
from t t2
where t2.fkid = t.fkid and t2.date < '2018-01-20'
);