使用SQL获取前面的行数据

时间:2011-05-16 18:44:19

标签: sql-server-2005

我有一个要求,我需要从上一行获取数据以用于计算,以便为当前行提供状态。这是一张历史表。如果数据在日期字段中发生了变化,前一行将告诉我。

我抬头使用游标,看起来有点复杂。这是最好的方式吗?

我还尝试为新字段赋值......

newField =(从Table1中选择field1,其中“previous row”)前一行是我似乎陷入困境的地方。我无法弄清楚如何选择当前行下面的行。

我正在使用SQL Server 2005

提前致谢。

3 个答案:

答案 0 :(得分:3)

这实际上取决于什么告诉你一行是“上一行”。但是,自我加入应该做你想做的事情:

select *
from Table1 this
  join Table2 prev on this.incrementalID = prev.incrementalID+1

答案 1 :(得分:3)

-- Test data
declare @T table (ProjectNumber int, DateChanged datetime, Value int)
insert into @T 
  select 1, '2001-01-01', 1 union all
  select 1, '2001-01-02', 1 union all
  select 1, '2001-01-03', 3 union all
  select 1, '2001-01-04', 3 union all
  select 1, '2001-01-05', 4 union all
  select 2, '2001-01-01', 1 union all
  select 2, '2001-01-02', 2

-- Get CurrentValue and PreviousValue with a Changed column
;with cte as
(
  select *,
    row_number() over(partition by ProjectNumber order by DateChanged) as rn
  from @T
)
select
  C.ProjectNumber,
  C.Value as CurrentValue,
  P.Value as PreviousValue,
  case C.Value when P.Value then 0 else 1 end as Changed
from cte as C
  inner join cte as P
    on C.ProjectNumber = P.ProjectNumber and
       C.rn = P.rn + 1

-- Count the number of changes per project  
;with cte as
(
  select *,
    row_number() over(partition by ProjectNumber order by DateChanged) as rn
  from @T
)
select
  C.ProjectNumber,
  sum(case C.Value when P.Value then 0 else 1 end) as ChangeCount
from cte as C
  inner join cte as P
    on C.ProjectNumber = P.ProjectNumber and
       C.rn = P.rn + 1
group by C.ProjectNumber

答案 2 :(得分:2)

如果您有以下表格

CREATE TABLE MyTable (
   Id            INT NOT NULL,
   ChangeDate    DATETIME NOT NULL,
   .
   .
   .
)

以下查询将返回MyTable的任何记录的上一条记录。

SELECT tbl.Id,
       tbl.ChangeDate,
       hist.Id,
       hist.ChangeDate
  FROM MyTable tbl 
       INNER JOIN MyTable hist
        ON hist.Id = tbl.Id 
       AND hiost.ChangeDate = (SELECT MAX(ChangeDate) 
                                 FROM MyTable sub 
                                WHERE sub.Id = tbl.Id AND sub.ChangeDate < tbl.ChangeDate)