使用SQL获取前面的行数据

Coo*_*oop 5 sql-server-2005

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

我已经查找了使用游标,看起来有点复杂.这是最好的方式吗?

我也试图为新领域赋予价值......

newField =(从Table1中选择field1,其中"previous row")前一行是我似乎卡住的地方.我无法弄清楚如何选择当前行下面的行.

我正在使用SQL Server 2005

提前致谢.

Mik*_*son 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
Run Code Online (Sandbox Code Playgroud)

  • 嘿,我把它放在适当的位置,效果很好!我看到了我所缺少的技能/概念。CTE 效果很好。我已经使用了临时表并尝试了视图,但 CTE 更容易。CTE 允许您将表连接到其自身,这非常有价值。与 row_numbers 结合使用效果很好。感谢您的帮助。 (2认同)