日期:2014-05-17  浏览次数:20580 次

求助一个SQL显示当前修改过的分数,并且还有原始记录的问题,在线等~~~~~~~~~~~~~
 
 这是现在的表结构
  updateuser score updatetime
  0006 5 2012-08-25
  0007 3 2012-08-26
  0009 4 2012-08-27
  0006 3 2012-08-28

现在想出这个效果

updateuser nowscore pastscore updatetime
 0007 3 5 2012-08-26
 0009 4 3 2012-08-27
 0006 3 4 2012-08-28

哪位大哥知道,小弟谢过啦


------解决方案--------------------
SQL code
 
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
*/

------解决方案--------------------
SQL code
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