gpt4 book ai didi

c# - 避免 SQL 查询、预订应用程序中的重复值

转载 作者:行者123 更新时间:2023-11-30 22:16:26 26 4
gpt4 key购买 nike

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

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 放在哪里?

您需要一张用于房间的 table 和一张用于预订的 table 。然后您需要一个子查询来查找与您请求的日期冲突的预订。这是您使用 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)
)

关于c# - 避免 SQL 查询、预订应用程序中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com