根据顶行过滤数据

时间:2012-12-09 16:49:19

标签: sql-server tsql datepart

我有一套类似

的句号
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))

有没有办法更好地做到这一点,或者更好地为大量数据优化代码?

1 个答案:

答案 0 :(得分: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
    )