1 -
create table changes(snapdate date,value int, uid int);
insert into changes values
('2013-04-22', 0, 1 ),
('2013-04-21', 1,1 ),
('2013-04-20', 1,1 ),
('2013-04-19', 1,1 ),
('2013-04-19', 0,2 ),
('2013-04-19', 1,1 ),
('2013-04-18', 0,1 ),
('2013-04-17', 0,1 ),
('2013-04-17', 1,2 ),
('2013-04-16', 1,1 ),
('2013-04-16', 0 ,2);
2 -
SELECT a.snapdate, a.value
FROM (
SELECT t1.*, COUNT(*) AS rank
FROM changes t1
LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate
GROUP BY t1.snapdate
) AS a
LEFT JOIN (
SELECT t1.*, COUNT(*) AS rank
FROM changes t1
LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate
GROUP BY t1.snapdate
) AS b ON a.rank = b.rank+1 AND a.value = b.value
WHERE b.snapdate IS NULL
ORDER BY a.snapdate DESC;
工作正常,但如何选择WHERE uid=2
例如?我不能使用临时表:
create temporary table changes_temp
as
select *
from changes
where uid = 2
http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html