这样的SQL查询语句如何实现?(asp网站)

来源:百度知道 编辑:UC知道 时间:2024/05/27 05:02:35
这样的SQL语句如何实现?
表 ticket
表字段 id city update(日期)
大概有如下数据(1万多条):
1 北京 2008-8-8
2 三亚 2008-8-12
6 上海 2008-8-27
9 广州 2008-8-28
10 天津 2008-9-1
.... .... 2008-9-3
.... .... 2008-9-8
.... .... 2008-9-9
.... .... 2008-9-10
.... .... 2008-9-12
.... .... 2008-9-14
.... .... 2008-9-20
.... .... ........
我要的结果是:
查询update=2008-9-1的时候
得出:如果存在这个日期2008-9-1,就得出2008-8-28,2008-9-1,2008-9-3,2008-9-4(也就是相邻的前一条,本身,后2条)对应的数据。
如果不存在这个日期2008-9-1,就得出2008-8-27,2008-8-28,2008-9-3,2008-9-8,(也就是相邻最近的前后2条的数据)。
这样的语句该怎么实现?知道的朋友帮忙一下。谢谢!
同一个日期还有很多的数据啊,不是一个日期只对应1条!

1.由于update不能作为表的列名,所以我做了一个例子:

create table A
(
id int identity primary key,
date datetime
)
go
if exists(select 1 from sysobjects where name='sp_test')
drop proc sp_test
go
create proc sp_test
(
@date datetime
)
as
declare @id int
declare @id_before int
declare @id_after int
select @id=id from A where date=@date
if(@id is not null)
begin
select @id_before=id from A where date=(select max(date) from A where date<@date)
select @id_after=id from A where date=(select max(date) from (select top 2 date from A where date>@date)as t)
select * from A where id between @id_before and @id_after
end
else
begin
select @id_before=id from A where date=(select min(date) from (select top 2 date from A where date<@date order by id desc)as t)
select top 4 * from A where id>=@id_before
end
go

insert A values(&#