[英]Compare between two dates in SQL query
I have a table, roomtype
, with the following data: 我有一个表
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
For a given date (ie, 2013-11-09
), I want to return the rate
for the matching season, where the given date falls within the StartSeason and EndSeason dates. 对于给定的日期(即
2013-11-09
),我想返回匹配季节的rate
,其中给定的日期在StartSeason和EndSeason日期之内。
ie, If my date is 2013-11-09
, then the rate should be 1700. If my date is 2012-09-09
, then the rate should be 800. 即,如果我的日期是
2013-11-09
,那么比率应该是1700。如果我的日期是2012-09-09
,那么比率应该是800。
How do I create a stored procedure or write the SQL query? 如何创建存储过程或编写SQL查询?
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
To improve the hard work of the query optimizer you can help him uses the UNION ALL operator inside subquery 为了改善查询优化器的辛苦工作,您可以帮助他在子查询中使用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
Of course, in addition to this query, it would be great provide the correct index 当然,除了此查询外,提供正确的索引也将是非常不错的
CREATE INDEX x ON Table1(StartSeason)
INCLUDE(EndSeason,Hotel_ID,Name,Rate,Season)
Plan Diagram 平面图
This should supply you with just the rate matching the season for the date in your query: 这应该为您提供查询中日期与季节匹配的汇率:
SELECT rate FROM roomtype
WHERE StartSeason >= '2013-11-09' AND EndSeason <= '2013-11-09';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.