在查询中包含上一个和下一个记录

时间:2014-04-24 17:25:41

标签: sql-server

我需要根据用户选择开始日期和结束日期的日期时间返回具有用户选择边界的折线图的查询。但是,当没有值接近所选边界的开始和结束时,数据通常是稀疏的并且抛出折线图的显示。

例如,如果我想选择2012年的所有数据,但第一条记录在3月之前不会出现,那么我的折线图将在3月开始其轴。

所以基本上我需要将前一个和后一个记录添加到按日期时间排序的返回集中。

现在,我只是使用带有子选择的UNION来使其工作,但看起来这可能是构建到SQL中的常见事情吗?

以下是工作查询的示例,我该如何改进呢?

--  SQL Server example
--  Compare between start and end dates
--  Union with previous and next records for bounds

SELECT 
    change_date as event_date,
    value_column
FROM 
    testing.dbo.change_log 
WHERE change_date BETWEEN '2012-01-01 00:00:00:000' AND '2013-01-01 00:00:00:000'
UNION ALL
SELECT * FROM (
    SELECT TOP 1 '2013-01-01 00:00:00:000' as event_date, value_column FROM     testing.dbo.change_log WHERE change_date > '2013-01-01 00:00:00:000' ORDER BY change_date ASC
) AS next_rec
UNION ALL
SELECT * FROM (
    SELECT TOP 1 '2012-01-01 00:00:00:000' as event_date, value_column FROM testing.dbo.change_log WHERE change_date < '2012-01-01 00:00:00:000' ORDER BY change_date DESC
) AS prev_rec
ORDER BY change_date;

1 个答案:

答案 0 :(得分:0)

这是怎么回事?我假设您正在使用它作为存储过程,并且当前正在为它提供两个输入参数。它与你如何做的并没有特别的不同,但可能会快一点。

declare @lowerbound as datetime
declare @upperbound as datetime

;with ordered as (
select *
, row_num =  row_number() over (order by change_date)
from change_log
)
select * 
from ordered
where row_num >= (select row_num from ordered where change_date = @lowerbound) -1 
    and row_num <= (select row_num from ordered where change_date = @upperbound) + 1