[英]How to group value within a certain date range or every certain days in SQL server
[英]sql - how to list properties not reserved within certain date-range?
预订表:
id | fk_property_id | arrival | departure
------+----------------+---------------------+---------------------
1 | 1 | 2013-01-11 14:00:00 | 2013-09-07 10:00:00
2 | 1 | 2013-02-12 14:00:00 | 2013-09-07 10:00:00
3 | 1 | 2013-03-29 14:00:00 | 2013-09-07 10:00:00
4 | 2 | 2013-04-29 14:00:00 | 2013-09-07 10:00:00
5 | 2 | 2013-05-29 14:00:00 | 2013-09-07 10:00:00
6 | 3 | 2013-06-29 14:00:00 | 2013-09-07 10:00:00
属性表:
id | title
-----+--------------------------------------------------------
1 | blah blah
2 | blah blah
3 | blah blah
4 | blah blah
5 | blah blah
6 | blah blah
7 | blah blah
8 | blah blah
9 | blah blah
10 | blah blah
我需要列出特定日期范围的可用属性。
例如用户输入日期范围:到达时间:2013-06-29 14:00:00出发日期:2013-07-14 10:00:00
我需要列出那些期间属性中未租用的所有内容。 我怎么做?
我认为它应该是一个左连接 - 但我无法绕过它。
这是正确的条件:
select p.*
from properties p left outer join
reservations r
on p.id = r.fk_property_id and
r.arrival < '2013-07-14 10:00:00' and
r.departure > '2013-06-29 14:00:00'
where r.id is null
这是逻辑。 首先,时间条件需要在on
子句中。 在where
子句中,它们与left outer join
冲突。
逻辑是,在较晚的日期之前没有到达并且在第一个日期之后没有离开的所有日子都可以使用房间。 这考虑了所有各种重叠可能性。
最后where
只是发现,因为没有保留可用的属性。
有两种方法:
LEFT JOIN
SELECT p.id, p.title
FROM properties p
LEFT JOIN reservations r
on p.id = r.fk_property_id
where arrival < '2013-06-29 14:00:00'
and departure > '2013-07-14 10:00:00'
and r.id is null
但是,由于你实际上是在执行反半连接,所以NOT EXISTS
对你来说可能更好:
select p.id, p.title
from properties p
where NOT EXISTS (
select 1
from reservations r
where where arrival > '2013-06-29 14:00:00'
and departure < '2013-07-14 10:00:00'
and p.id = r.fk_property_id);
您可能希望在LEFT OUTER JOIN
表中使用IS NULL
。 意味着在该特定属性的预订表中找不到任何内容。
SELECT *
FROM properties LEFT OUTER JOIN reservations ON properties.id = reservations.fk_property_id AND a
WHERE arrival > '2013-06-29 14:00:00'
AND departure < '2013-07-14 10:00:00'
AND reservations.arrival IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.