我想从单个表中获取信息,其中我将显示每条记录的最新事务,同时记录它之前的事务。
|id | account_no | date1 | price |
|1 | 101 |2018-04-10 | 100 |
|2 | 101 |2018-04-7 | 200 |
|3 | 102 |2018-04-10 | 300 |
|account_no|latest_entry(date)|price |previous_entry(date)|price |
|101 |2018-04-10 |100 |2018-04-7 |200 |
|102 |2018-04-10 |300 |null |0 |
这是我的查询:
select max(date_recorded) as ldte, test_tbl.* from test_tbl group by account_no order by date_recorded desc
提前致谢。
您可以通过执行以下操作获得对先前信息的引用:
select t.*,
(select t2.id
from t t2
where t2.account_no = t.account_no and t2.date1 < t.date1
order by t2.date1 desc
limit 1
) as prev_id
from t ;
将此用作子查询以连接回原始表:
select t.*, tprev.date, tprev.price
from (select t.*,
(select t2.id
from t t2
where t2.account_no = t.account_no and t2.date1 < t.date1
order by t2.date1 desc
limit 1
) as prev_id
from t
) t join
t tprev
on t.prev_id = tprev.id;
您可以通过添加以下where
子句将其限制为最近的日期:
where t.id = (select t2.id
from t t2
where t2.account_no = t.account_no
order by t2.date desc
limit 1
)
这可以在外部查询或子查询中进行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句