添加一列以查询输出,其中包含mysql中的上一行列值

时间:2017-04-06 08:23:34

标签: mysql sql

Coulmns出席会议记录:

    Subject<Integer> subject = PublishSubject.create();
    subject.subscribe(new Consumer<Integer>() {
        @Override
        public void accept(@NonNull Integer integer) throws Exception {
            System.out.println("item = " + integer);
        }
    });
    Observable.just(1,2).doOnNext(new Consumer<Integer>() {
        @Override
        public void accept(@NonNull Integer e) throws Exception {
            subject.onNext(e);
        }
    }).subscribe();

    subject.onNext(3);

要在查询中返回的Coulmns:

 id          toDate                                      
-----      ----------       
111          02-03-2017                                               

111          20-03-2017                                                

111          01-04-2017       

111          05-04-2017              

我有查询后面的查询 id toDate fromDate ----- ---------- ---------- 111 02-03-2017 01-01-01 <---(always first record value) 111 20-03-2017 02-03-2017 <---(rest of the rows should be previous record's toDate value) 111 01-04-2017 20-03-2017 111 DatedNow 01-04-2017 <-- last record toDate should be current date

需要为查询添加查询才能获得所需的输出?

1 个答案:

答案 0 :(得分:3)

您可以使用以下查询执行此操作:

SELECT id,toDate,fromDate
FROM (
    SELECT m.*, @fromDate AS fromDate
    ,@fromDate := m.toDate
    FROM myHistory m
    CROSS JOIN (SELECT @fromDate:='1901-01-01') AS init
    ORDER BY toDate
) AS result;

<强>样品

mysql> SELECT id,toDate,fromDate
    -> FROM (
    ->     SELECT m.*, @fromDate AS fromDate
    ->     ,@fromDate := m.toDate
    ->     FROM myHistory m
    ->     CROSS JOIN (SELECT @fromDate:='1901-01-01') AS init
    ->     ORDER BY toDate
    -> ) AS result;
+-----+------------+------------+
| id  | toDate     | fromDate   |
+-----+------------+------------+
| 111 | 2017-03-02 | 1901-01-01 |
| 111 | 2017-03-20 | 2017-03-02 |
| 111 | 2017-04-01 | 2017-03-20 |
+-----+------------+------------+
3 rows in set (0,00 sec)

mysql>