1

我有一张表,roomtype其中包含以下数据:

Hotel_ID    Name     Rate   Season    StartSeason   EndSeason
   1      Deluxe/Ac  2700   New Year  2013-12-20    2014-01-10
   1      Deluxe/Ac  3100   31 Dec    2013-12-31    2012-12-31
   1      Deluxe/Ac  1700   Diwali    2013-11-01    2013-11-15
   1      Deluxe/Ac  800    Normal    NULL          NULL

对于给定日期(即2013-11-09),我想返回rate匹配季节的日期,其中给定日期在 StartSeason 和 EndSeason 日期内。

即,如果我的日期是2013-11-09,那么费率应该是 1700。如果我的日期是2012-09-09,那么费率应该是 800。

如何创建存储过程或编写 SQL 查询?

4

3 回答 3

2
select top 1 hotel_id, rate
from roomtype r
where '2013-11-09' between startseason and endseason
or startseason is null and endseason is null
order by case when startseason is null and endseason is null then 2 else 1 end
于 2013-09-21T10:56:08.557 回答
1

为了提高查询优化器的工作效率,您可以帮助他在子查询中使用 UNION ALL 运算符

SELECT TOP 1 *
FROM (SELECT TOP 1 *
      FROM Table1
      WHERE @date BETWEEN StartSeason AND EndSeason
      UNION ALL
      SELECT TOP 1 *
      FROM Table1
      WHERE StartSeason IS NULL
      ) x
ORDER BY StartSeason DESC

当然,除了这个查询,提供正确的索引就好了

CREATE INDEX x ON Table1(StartSeason)
  INCLUDE(EndSeason,Hotel_ID,Name,Rate,Season)

平面图

在此处输入图像描述

见演示SQLFiddle

于 2013-09-21T11:34:35.447 回答
0

这应该只为您提供与查询中日期的季节相匹配的费率:

SELECT rate FROM roomtype 
   WHERE StartSeason >= '2013-11-09' AND EndSeason <= '2013-11-09';
于 2013-09-21T11:17:16.700 回答