第一次在这里问问题时,我正在使用Visual Studio 2015在C#上编写预订应用程序,但是尝试在数据网格视图上显示空闲空间时遇到了问题,这是我正在使用的查询:

SELECT clientID, cost, arrival, roomNumber, resvNum, departure, size
FROM roomswithresvView
WHERE (roomNumber NOT IN
       (SELECT  roomNumber
          FROM    roomswithresvView AS roomswithresvView_1
           WHERE   (arrival BETWEEN @date1 AND @date2)
             OR (departure BETWEEN @date1 AND @date2)))


问题是,如果一个房间有多个预订,查询将多次显示该预订,我尝试使用DISTINCT,但是我只能处理一列,而我无法使GROUP BY工作。

感谢您的关注。

Query Sample

例如,如果我使用2016-07-06作为date1和2016-07-07作为date2测试查询,它将重复房间1005,因为它在数据库上有两个保留。

最佳答案

您将DISTINCT放在哪里?

您需要一个用于房间的桌子和一个用于预订的桌子。然后,您需要一个子查询来查找与您要求的日期相冲突的预订。在这里使用DISTINCT。然后,您需要一个外部查询来查找子查询中未返回的所有房间。不要忘记您已有的预订开始于请求的日期之后并在其之后结束的情况!放在一起,你得到了...

 insert into room(costPerNight, roomNumber, size)
 values
 (55, 1, 13),
 (65, 2, 15),
 (85, 3, 20)
 ;

 create table reservation(
 id int identity (1,1) not null,
 roomId int not null,
 dateIn date not null,
 dateOut date not null
 )

 insert into reservation (roomId, dateIn, dateOut)
 values
 (1,'2016-07-01','2016-07-03'),
 (1,'2016-07-05','2016-07-08'),
 (2,'2016-07-01','2016-07-08')
 */

 declare @requestedDateIn date = '2016-07-03'
 declare @requestedDateOut date = '2016-07-05';

 select * from room where id not in(
 --find clashing reservations
 select distinct roomId from reservation where
 (dateOut > @requestedDateIn and dateOut < @requestedDateOut)
 or (dateIn > @requestedDateIn and dateIn < @requestedDateOut)
 or (dateIn < @requestedDateIn and dateOut > @requestedDateOut)
 )

09-26 23:17
查看更多