I have a table, roomtype
, with the following data:
我有一个tabletype 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),我想返回匹配季节的费率,其中给定日期在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查询?
3 个解决方案
#1
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
#2
1
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
See demo on SQLFiddle
请参阅SQLFiddle上的演示
#3
0
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';
#1
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
#2
1
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
See demo on SQLFiddle
请参阅SQLFiddle上的演示
#3
0
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';