CREATE PROCEDURE [dbo].[GetToursList](
@toCity nvarchar(30)
, @toCountry nvarchar(30)
, @departureDate date
, @amountNights int)
AS
BEGIN
SELECT
hotels.Name as HotelName
,cities.Name as CityName
,countrys.Name as CounrtyName
,(select min((select hotelsRooms.price from hotelsRooms where hotelsRooms.HotelID = hotels.Id))) as MinPrice// здесь мучаюсь
,hotels.Rating as Stars
,hotels.Line as Line
,hotels.DistanceToAirport as DistToAirport
,hotels.DistanceToBeach as DistTobeach
FROM dbo.Tours
INNER JOIN dbo.Countrys as countrys
ON Tours.CountryID = countrys.Id
INNER JOIN dbo.Cities as cities
ON Tours.CityID = cities.Id
INNER JOIN dbo.Hotels as hotels
ON Tours.HotelID = hotels.Id
INNER JOIN dbo.HotelsRooms as hotelsRooms
ON hotelsRooms.HotelID = hotels.Id
WHERE
(@toCity is null or(Tours.CityID = (select cities.Id from cities where cities.Name = @toCity)))
or
(@toCountry is null or(Tours.CountryID = (select countrys.Id from countrys where countrys.Name = @toCountry)))
END
(69,1): SQL72014: .Net SqlClient Data Provider: Msg 130, Level 15, State 1, Procedure GetToursList, Line 12 Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
(58,0): SQL72045: Script execution error. The executed script:
(SELECT MIN( hotelsRooms.price) FROM hotelsRooms WHERE hotelsRooms.HotelID = hotels.Id ) as MinPrice
[Tours]
[HotelID] INT NOT NULL
[CityID] INT NOT NULL,
[CountryID] INT NOT NULL,
Гостиница может быть без города, город — без страны? Нет. Нужно удалить поля город и страна, а использовать связанные таблицы.SELECT Hotels.[Name] AS HotelName,
Cities.[Name] AS CityName,
Countrys.[Name] AS CounrtyName,
(SELECT MIN(Price)
FROM HotelsRooms
WHERE (HotelID = Hotels.ID)) AS MinPrice,
Hotels.Rating AS Stars,
Hotels.Line,
Hotels.DistanceToBeach,
Hotels.DistanceToAirport
FROM Hotels
INNER JOIN Cities ON Hotels.City = Cities.ID
INNER JOIN Countrys ON Cities.CountryID = Countrys.ID
WHERE ((@toCity IS NULL) OR (Cities.[Name] = @toCity))
AND ((@toCountry IS NULL) OR (Countrys.[Name] = @toCountry))
SELECT MIN(Price) FROM HotelsRooms WHERE (HotelID = 14)
Потом перенести его вSELECT (SELECT MIN(Price) AS Expr1
FROM HotelsRooms
WHERE (HotelID = 14)) AS Expr1
FROM Hotels
WHERE (Id = 14)
Связать таблицы SELECT (SELECT MIN(Price) AS Expr1
FROM HotelsRooms
WHERE (HotelID = Hotels.Id)) AS MinPrice
FROM Hotels
WHERE (Id = 14)
declare @minmaxprices table (hotel_id int, min_price decimal, max_price decimal)
insert into @minmaxprices
select hotel_id, min(price), max(price) from hotelrooms group by hotel_id
select
…
[самая низкая цена] = minmaxprices.minprice
…
from hotels
…
left join @minmaxprices as minmaxprices on minmaxprices.hotel_id=hotels.hotel_id
;with cte_min_max_prices(hotel_id, minprice, maxprice)
as ( select hotel_id, min(price), max(price) from hotelrooms group by hotel_id )
select
…
[самая низкая цена в отеле] = cte_min_max_prices.minprice
...
from hotels
….
left join cte_min_max_prices on cte_min_max_prices.hotel_id=hotels.hotel_id