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))

有没有办法做得更好,或者针对大量数据更好地优化代码?

4

1 回答 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
    )
于 2012-12-10T03:14:19.173 回答