此脚本检索只有所需房间的酒店。如果酒店只有一个必要的房间,那么它被排除在酒店之外。
更新 15.01.2013
IF OBJECT_ID('tempdb.dbo.#RoomParams') IS NOT NULL DROP TABLE dbo.#RoomParams
SELECT SUM(rooms) AS rooms, adults
INTO dbo.#RoomParams
FROM (VALUES(1, 2), -- 1 room with 2 adults
(1, 2), -- 1 room with 2 adults
(1, 3)) -- 1 room with 3 adults
p(rooms, adults)
GROUP BY adults
;WITH cte AS
(
SELECT h.hotel_id, h.hotel_name, h.location, r.room_type, r.price,
SUM(avail_rooms) OVER (PARTITION BY h.hotel_id, r.max_adults_allowed) AS cnt,
r.max_adults_allowed
FROM CONTRACT c JOIN ROOM r ON c.contract_id = r.contract_id AND c.hotel_id = r.hotel_id
JOIN HOTEL h ON c.hotel_id = h.hotel_id
WHERE c.valid_from >= '20130114' AND c.valid_to <= '20130115' --check in and check out dates comparison
AND h.location IN ('loc4') --requested location
)
SELECT *
FROM cte s
WHERE
NOT EXISTS (
SELECT rp.adults
FROM dbo.#RoomParams rp
EXCEPT
SELECT st.max_adults_allowed
FROM cte st JOIN dbo.#RoomParams r ON st.cnt >= r.rooms AND st.max_adults_allowed = r.adults
WHERE st.hotel_id = s.hotel_id
) AND s.max_adults_allowed IN (SELECT adults FROM dbo.#RoomParams)
SQLFiddle上的演示
如果您想检索所有至少有一个选项的酒店
IF OBJECT_ID('tempdb.dbo.#RoomParams') IS NOT NULL DROP TABLE dbo.#RoomParams
SELECT rooms, adults
INTO dbo.#RoomParams
FROM (VALUES(1, 2), -- 1 room with 2 adults
(1, 2), -- 1 room with 2 adults
(1, 3)) -- 1 room with 3 adults
p(rooms, adults)
;WITH cte AS
(
SELECT h.hotel_id, h.hotel_name, h.location, r.room_type, r.price,
SUM(avail_rooms) OVER (PARTITION BY h.hotel_id, r.max_adults_allowed) AS cnt,
r.max_adults_allowed
FROM CONTRACT c JOIN ROOM r ON c.contract_id = r.contract_id AND c.hotel_id = r.hotel_id
JOIN HOTEL h ON c.hotel_id = h.hotel_id
WHERE c.valid_from >= '20130114' AND c.valid_to <= '20130115' --check in and check out dates comparison
AND h.location IN ('loc4') --requested location
)
SELECT hotel_name, location, room_type, price, max_adults_allowed, cnt
FROM cte c
WHERE EXISTS (
SELECT 1
FROM dbo.#RoomParams r
WHERE c.cnt >= r.rooms AND c.max_adults_allowed = r.adults
)