【问题标题】:Filtering data based on a top row根据顶行过滤数据
【发布时间】:2012-12-09 16:49:18
【问题描述】:

我有一组类似的时期

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

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

【问题讨论】:

    标签: sql-server tsql datepart


    【解决方案1】:

    嗯,不清楚你说的第一行是什么意思。第一期预约?您是否使用它来测试保留是否从正确的 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
        )
    

    【讨论】:

    • 是的,但我也想 a) 返回受预订日期影响的所有行,b) 检查与预订开始日期相对应的第一行是否也对应于强制性 DOW (datefirst = row.DOW)
    • 好的,所以:返回预订的所有期间,但前提是开始日期落在允许的 DOW 上,是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2019-04-29
    相关资源
    最近更新 更多