2016-01-20 61 views
0

如何獲取mysql中的前一行? 比如我有數據:MySQL:得到以前的行分組

serial........date..............value 
xxx...........2016.01.03...3 
xxx...........2016.01.02...2 
xxx...........2016.01.01...1 
yyy...........2016.01.03...3 
yyy...........2016.01.02...2 
yyy...........2016.01.01...1 

我需要得到這個:

serial........date..............value..value_prev 
xxx...........2016.01.03...3........2 
xxx...........2016.01.02...2........1 
xxx...........2016.01.01...1........null 
yyy...........2016.01.03...3........2 
yyy...........2016.01.02...2........1 
yyy...........2016.01.01...1........null 

diferent例如:

serial........date.........value....value_prev 
xxx...........2016.01.03...12.......5 
xxx...........2016.01.02...5........3 
xxx...........2016.01.01...3........null 
yyy...........2016.01.03...9........6 
yyy...........2016.01.02...6........1 
yyy...........2016.01.01...1........null 
+0

是按計數順序總是值是多少?你能向我們展示這個問題的更復雜的樣本數據嗎? –

+0

加油。試試吧! – Strawberry

+0

在基礎知識中,我需要按序列排序並按日期排序 –

回答

0
DROP TABLE IF EXISTS my_table; 

CREATE TABLE my_table 
(serial CHAR(3) NOT NULL 
,date DATE NOT NULL 
,value INT NOT NULL 
,PRIMARY KEY (serial,date) 
); 

INSERT INTO my_table VALUES 
('xxx','2016-01-03',12), 
('xxx','2016-01-02',5), 
('xxx','2016-01-01',3), 
('yyy','2016-01-03',9), 
('yyy','2016-01-02',6), 
('yyy','2016-01-01',1); 

SELECT x.* 
    , MAX(y.value) prev 
    FROM my_table x 
    LEFT 
    JOIN my_table y 
    ON y.serial = x.serial 
    AND y.date < x.date 
GROUP 
    BY x.serial 
    , x.date; 
+--------+------------+-------+------+ 
| serial | date  | value | prev | 
+--------+------------+-------+------+ 
| xxx | 2016-01-01 |  3 | NULL | 
| xxx | 2016-01-02 |  5 | 3 | 
| xxx | 2016-01-03 | 12 | 5 | 
| yyy | 2016-01-01 |  1 | NULL | 
| yyy | 2016-01-02 |  6 | 1 | 
| yyy | 2016-01-03 |  9 | 6 | 
+--------+------------+-------+------+