选择现有列的值作为具有一行移位的新列的值

时间:2013-04-19 05:58:01

标签: sql sql-server select

我有一个问题,如果你帮忙我会很感激。

在下面的图片中,我想构建一个名为“recent score”的新列 如您所见,最近得分是用户上次约会时得分。如果我们按日期排序行,则最近得分是下一行的得分值。

enter image description here

我编写了以下代码,但这是错误的:(

  SELECT [user-name],
         [submissions],
         [date],
         [score]

         (SELECT [score]
                 FROM [top-concept6] tc6
                 WHERE tc6.[user-name]=[top-concept6].[user-name]
                 AND tc6.[date]= (SELECT  TOP(1) [date] 
                 FROM [top-concept6] tcc6  
                 WHERE [date]<[top-concept6].[date] ORDER BY [date] DESC)) AS [recent-score]

   FROM [top-concept6]

这是sql fiddle:http://sqlfiddle.com/#!3/74e3f

2 个答案:

答案 0 :(得分:1)

请尝试:

select 
    *,
    (select top 1 b.score from [top-concept6] b where b.[user-name]=a.[user-name] and b.date<a.date order by b.date desc) [Recent Score]
from 
    [top-concept6] a

答案 1 :(得分:1)

select *, 
(select top 1 score from [top-concept6]
 where [user-name]=t1.[user-name]
       and [date]<t1.[date]
 order by date desc    
) recent_score
from [top-concept6] t1

SQLFiddel demo