22,210
社区成员
发帖
与我相关
我的任务
分享
if object_id('tb') is not null drop table tb
-- 创建数据表
create table tb
(
班级名 int,
上课时间 datetime,
人数 int
)
go
--插入测试数据
insert into tb select 1,'2010-10-5',4
union all select 1,'2010-9-5',5
union all select 1,'2010-10-6',6
go
--代码实现
select 班级名,人数
,和上次课人数的差=人数-isnull((
select top 1 人数
from tb
where 班级名=t.班级名 and 上课时间<t.上课时间
order by 上课时间 desc),0)
from tb t
order by 上课时间 desc
班级名 人数 和上次课人数的差
---------------------------------
1 6 2
1 4 -1
1 5 5
/*
1 1 2010-09-05 00:00:00.000 5 5
2 1 2010-10-05 00:00:00.000 4 -1
3 1 2010-10-06 00:00:00.000 6 2
*/
/*if object_id('S') is not null drop table S
create table S(classid int,classtime datetime,num int)
insert into S
select 1,'2010-10-5',4 union all
select 1,'2010-9-5',5 union all
select 1,'2010-10-6',6*/
with t as (select idd=row_number() over (order by classtime),* from S)
select t.*,和上次课人数的差=t.num-isnull(a.num,0) from t left join t a on t.idd=a.idd+1
use test
go
if object_id('test.dbo.tb') is not null drop table tb
-- 创建数据表
create table tb
(
班级名 int,
上课时间 datetime,
人数 int
)
go
--插入测试数据
insert into tb select 1,'2010-10-5',4
union all select 1,'2010-9-5',5
union all select 1,'2010-10-6',6
go
--代码实现
select 班级名,人数
,和上次课人数的差=人数-isnull((
select top 1 人数
from tb
where 班级名=t.班级名 and 上课时间<t.上课时间
order by 上课时间 desc),0)
from tb t
/*测试结果
班级名 人数 和上次课人数的差
---------------------------------
1 4 -1
1 5 5
1 6 2
(3 行受影响)
*/