比较SQL查询中的两个日期

时间:2013-09-21 10:54:23

标签: c# asp.net sql sql-server ado.net

我有一张表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查询?

3 个答案:

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

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

计划图

enter image description here

请参阅SQLFiddle

上的演示

答案 2 :(得分:0)

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

SELECT rate FROM roomtype 
   WHERE StartSeason >= '2013-11-09' AND EndSeason <= '2013-11-09';