日期:2014-05-17 浏览次数:20580 次
declare @T table(updateuser varchar(4), score int, updatetime datetime) insert into @T select '0006', 5, '2012-08-25' union all select '0007', 3, '2012-08-26' union all select '0009', 4, '2012-08-27' union all select '0006', 3, '2012-08-28' ;with cte as ( select row_number() over(order by updatetime) rn,* from @T ) select * from ( select updateuser, score as nowscore, pastscore=(select score from cte where t.rn=rn+1), convert(varchar(10),updatetime,120) updatetime from cte t ) tt where tt.pastscore is not null /* updateuser nowscore pastscore updatetime ---------- ----------- ----------- ---------- 0007 3 5 2012-08-26 0009 4 3 2012-08-27 0006 3 4 2012-08-28 */
------解决方案--------------------
USE tempdb GO CREATE TABLE test ( updateuser VARCHAR(10), score INT, updatetime SMALLDATETIME ); INSERT INTO test SELECT '0006',5,'2012-08-25' UNION ALL SELECT '0007',3,'2012-08-26' UNION ALL SELECT '0009',4,'2012-08-27' UNION ALL SELECT '0006',3,'2012-08-28' SELECT ROW_NUMBER()OVER (ORDER BY updatetime ) AS id ,* INTO #t FROM test /* updateuser nowscore pastscore updatetime 0007 3 5 2012-08-26 0009 4 3 2012-08-27 0006 3 4 2012-08-28 */ SELECT * FROM #t SELECT updateuser ,score AS nowscore,(SELECT b.score FROM #t b WHERE a.id=b.id+1 ) AS pastcsroe,a.updatetime FROM #t a WHERE (SELECT b.score FROM #t b WHERE a.id=b.id+1 ) IS NOT NULL