MySQL抓取:需要一些建议

时间:2018-04-16 01:13:50

标签: mysql sql

我想从单个表中获取信息,其中我将显示每条记录的最新交易,同时记录其先前的交易。

表:

|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

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式获取对先前信息的引用:

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
             )

这可以在外部查询中或在子查询中。