2012-12-09 134 views
0

我有一个像过滤数据

PERIODID PERIODSTART PERIODEND PRICE STARTDOW 
1  2012-12-01 2012-12-10 10 6 
2  2012-12-11 2012-12-20 20 -1 
3  2012-12-21 2012-12-30 30 -1 

一套时期东西意思就是保留在第1期开始,必须在星期六,而不是周期2和3

如果我从2012-12-10 - 2012-12-15有预订我想> - 过滤日期为几天(不是问题) - 检查是否保留星期六开始。过滤器应该只用于顶部(或第一行),我不知道如何做到这一点。如果预订没有在星期六开始,则不应返回任何行。

我试图

select * from periods p 
where 
((@ReservationStart between p.periodstart and p.periodend) 
or 
(@ReservationEnd between p.periodstart and p.periodend)) 
and ((select top 1 datepart(weekday, startdow) from periods where p.hotelID = period.hotelID order by period.periodstart) in (@datepart(weekday, @ReservationStart), -1)) 

有没有办法做的更好,或者优化代码对于大数据量的更好吗?

回答

0

嗯,不清楚你的意思是第一行。预订的第一个阶段?您是否使用此测试来测试预订是否在正确的DOW上开始?

set datefirst 1 -- make Monday return 1 when calling datepart(day,...) 

-- if reservation starts on STARTDOW, this will return a single row. 
-- if not, it will return an empty record set 
select top (1) * from periods p 
where @ReservationStart between p.periodstart and p.periodend 
    and p.STARTDOW in (-1, datepart(day,@ReservationStart)) 

编辑

也许这样的事情呢?

set datefirst 1 -- make Monday return 1 when calling datepart(day,...) 

-- return all periods of the reservation 
-- modify as necessary if you only want the first and last periods, as in your example. 
select * from periods p 
where p.periodend >= @ReservationStart 
    and p.periodstart <= @ReservationEnd 
    -- but only if the start date falls on an allowed DOW 
    and exists (
    select * from periods p2 
    where @ReservationStart between p2.periodstart and p2.periodend 
     and p2.STARTDOW in (-1, datepart(day,@ReservationStart)) 
     and p2.hotelID = p.hotelID -- necessary correlation condition 
    ) 
+0

是的,但我也想一)返回受预约日期的所有行,b)检查如果对应于预定开始日期的第一行还对应于强制性DOW(DATEFIRST = row.DOW) – mko

+0

OK ,那么:返回预订的所有阶段,但仅限于开始日期落在允许的DOW中,是的? –