0

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

4

2 回答 2

0

添加 where 子句:

SELECT a.snapdate, a.value 
FROM ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  WHERE t1.uid = 2
  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 
  WHERE t1.uid = 2
  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;

sqlfiddle

于 2013-06-13T08:25:50.987 回答
0

尝试在子查询中添加 WHERE 子句

    SELECT a.snapdate, a.value 
FROM ( 
  SELECT t1.*, COUNT(*) AS rank 
  FROM changes t1
  LEFT JOIN changes t2 ON t1.snapdate >= t2.snapdate 
  WHERE t2.uid=t1.uid AND t2.uid=2
  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 
  WHERE t2.uid=t1.uid AND t2.uid=2
  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;

为测试创建了 SQLFiddle。那是你要的吗 ?您没有解释查询的目标

于 2013-06-13T08:26:17.553 回答