我有一个要求,我需要从前一行获取数据,以便在计算中使用,以便为当前行提供状态.这是一张历史表.如果数据在日期字段中发生了更改,则前一行将告诉我.
我已经查找了使用游标,看起来有点复杂.这是最好的方式吗?
我也试图为新领域赋予价值......
newField =(从Table1中选择field1,其中"previous row")前一行是我似乎卡住的地方.我无法弄清楚如何选择当前行下面的行.
我正在使用SQL Server 2005
提前致谢.
-- 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)
| 归档时间: |
|
| 查看次数: |
4118 次 |
| 最近记录: |