嵌套查询问题???

tamebo 2007-03-16 12:53:04
表:
ID Time
4 2007-1-1
1 2007-1-3
2 2007-1-4
4 2007-1-5

当插入数据后 2007-1-2
自动取出取出最靠近的时间段 2007-1-1 和 2007-1-3 的id号4和1

...全文
211 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2007-03-16
  • 打赏
  • 举报
回复
if object_id('pubs..tb') is not null
drop table tb
go

create table tb(ID int,Time datetime)
insert into tb(ID,Time) values(4, '2006-1-1')
insert into tb(ID,Time) values(4, '2007-1-1')
insert into tb(ID,Time) values(1, '2007-1-3')
insert into tb(ID,Time) values(2, '2007-1-4')
insert into tb(ID,Time) values(4, '2007-1-5')
go

declare @dt as datetime
set @dt = '2007-01-02'

select * from tb where time in
(
select max(time) as time from tb where datediff(day, time , @dt) > 0
union all
select min(time) as time from tb where datediff(day, time , @dt) < 0
)

drop table tb

/*
ID Time
----------- ------------------------------------------------------
4 2007-01-01 00:00:00.000
1 2007-01-03 00:00:00.000

(所影响的行数为 2 行)
*/
paoluo 2007-03-16
  • 打赏
  • 举报
回复
Create Table TEST
(ID Int,
Time Varchar(10))
Insert TEST Select 4, '2007-1-1'
Union All Select 1, '2007-1-3'
Union All Select 2, '2007-1-4'
Union All Select 4, '2007-1-5'
GO
Declare @Time DateTime
Select @Time = '2007-1-2'
Select
ID
From
TEST
Where
[Time]
In (Select TOP 1 [Time] From TEST Where [Time] > @Time Order By [Time]
Union All
Select TOP 1 [Time] From TEST Where [Time] < @Time Order By [Time] Desc)
GO
Drop Table TEST
/*
ID
4
1
*/
comszsoft 2007-03-16
  • 打赏
  • 举报
回复
create proc p_add
@time datetime,
@previd int output,
@nextid int output
as

insert into t1(time) values(@time)

set @previd=isnull((select top 1 [id] from t1 where time < @time order by time ),0)
set @nextid=isnull((select top 1 [id] from t1 where time > @time order by time ),0)

go

27,581

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧