2012-11-18 50 views
1

我们有一个Fixtures jQuery传送带滚筒,显示已完成和即将到来的夹具。请参阅News Roller上方的http://www.allblacks.com/。目前这是硬编码。SQL Server:获取记录的范围取决于匹配夹具的好处

我们希望最多可以滚动5条记录。滚筒应显示最近完成的夹具,向前箭头显示接下来的两个即将到来的夹具,后退箭头显示最近完成的两个夹具。这通过滚筒js自动发生,即如果返回五个记录,滚筒将显示中心记录,即记录#3。

那么,如何写出查询以提取五条记录,其中THIRD记录是最近完成的夹具?

以下是数据库结构。夹具的完成由eventDateTime决定。

事件

eventID Event      eventDateTime 
------------------------------------------------- 
2016  Australia v All Blacks  2012-12-11 22:00:00.000 
2015  South Africa v Australia 2012-12-04 03:00:00.000 
2014  South Africa v Australia 2012-11-28 03:00:00.000 
2013  South Africa v All Blacks 2012-11-22 03:00:00.000 
2012  All Blacks v Australia  2012-11-07 19:35:00.000 
2011  Australia v All Blacks  2012-10-31 22:00:00.000 
2010  Australia v South Africa 2012-10-24 22:00:00.000 
.... 

编辑

所以,eventID 2012年是最近完成的比赛截至当前日期(2012年11月18日),我想记录返回如下所示,其中eventID 2012处于中间,即第三条记录:

eventID Event      eventDateTime 
------------------------------------------------- 
2010  Australia v South Africa 2012-10-24 22:00:00.000 
2011  Australia v All Blacks  2012-10-31 22:00:00.000 
2012  All Blacks v Australia  2012-11-07 19:35:00.000 
2013  South Africa v All Blacks 2012-11-22 03:00:00.000 
2014  South Africa v Australia 2012-11-28 03:00:00.000 

回答

0
Select * from 
(
select top 3 * from #event where eventDateTime<=(getdate()) order by eventDateTime desc 
UNION 
select top 2 * from #event where eventDateTime>(getdate()) 
) a 
order by eventDateTime 

的另外可能是

Select * from 
(
select top 3 *,1 - row_number() over (order by GetDate() - eventDateTime) as Sequence from #event where eventDateTime<=(getdate()) order by eventDateTime desc 
UNION 
select top 2 *, row_number() over (order by eventDateTime - GetDate()) from #event where eventDateTime>(getdate()) 
) a 
order by eventDateTime 
1

你可能只需要这样:

select eventID, Event, eventDateTime 
from 
    (select top 3 * 
    from events 
    where DATEADD(dd, DATEDIFF(dd,0,eventDateTime), 0) <= getdate() 
    order by eventDateTime) first 
union all 
select eventID, Event, eventDateTime 
from 
    (select top 2 * 
    from events 
    where DATEADD(dd, DATEDIFF(dd,0,eventDateTime), 0) > getdate() 
    order by eventDateTime) second