比較第二行到上一行:
SELECT cur.date, prev.color "before", cur.color now
FROM tbl cur
LEFT JOIN tbl prev ON cur.id = prev.id + 1
WHERE cur.id > 1 -- start detecting changes from second row
AND prev.color <> cur.color
現場測試:http://sqlfiddle.com/#!2/0c146/1
編輯
在非連續數據甚至工作。查詢可以,如果有CTE功能更succint在MySQL
create table tbl
(
id int,
date date,
color text
);
insert into tbl(id,date,color)
select 1,'2012-1-1','black' union
select 2,'2012-1-3','red' union
select 3,'2012-1-7','red' union
select 4,'2012-1-15','red' union
select 5,'2012-1-21','green' ;
set @rx = 0;
set @ry = 0;
select cur.date, prev.color as "before", cur.color as "now"
from (select *, @ry := @ry + 1 as series from tbl order by date) as cur
left join (select *, @rx := @rx + 1 as series from tbl order by date) as prev
on cur.series = prev.series + 1
where cur.series > 1
and prev.color <> cur.color
現場測試:http://sqlfiddle.com/#!2/b9443/2
這是功課?如果是這樣,你應該這樣標記。此外,你到目前爲止嘗試過哪些方法? – 2012-04-19 15:20:59
輸出日期不明確,它指的是哪個日期? – 2012-04-19 15:31:15