我是SQL新手,需要帮助将两个子查询与SQL中的主查询组合(JOIN)。这就是我所拥有的。 *每个查询独立于另一个查询。最终的结果是,我将检索每个度假村的住宿数量,检索每个度假村所有住宿的最低成本,并将这些结果加入度假村类型和度假村列表。
DB Schema
Table 1 - Resort -
resort_id (PK)
resort_type_id (FK)
name
Table 2 - Resort_type -
resort_type_id (PK)
resort_type
Table 3 - Accommodations -
accommodations_id (PK)
resort_id (FK)
description
cost_per_night
查询
SELECT Resort.name, Resort_type, Acc.Accommodations, Low.min_price
FROM
(SELECT resort.name AS resort_name, Resort_type.resort_type
FROM Resort
INNER JOIN Resort_type
ON Resort.resort_type_id = Resort_type.resort_type_id
(SELECT resort_id, Count(resort_id) AS Accommodations
FROM Accommodations
GROUP BY resort_id) AS Acc
(SELECT resort_id, Min(cost_per_night) AS min_price
FROM Accommodations
GROUP BY resort_id) AS Low
非常感谢任何指导。我很难想象这应该如何结合在一起。
答案 0 :(得分:2)
下面的查询列出了每个度假村及其类型以及住宿数量和每晚最低成本。
select
r.name,
t.resort_type as type,
count(a.accommodations_id) as accommodations,
min(cost_per_night) as lowestcost
from resort r
inner join resort_type t
on t.resort_type_id = r.resort_type_id
left join accommodations a
on a.resort_id = r.resort_id
group by r.name, t.resort_type
答案 1 :(得分:0)
这是你正在寻找的东西:
SELECT
r.name,
rt.resort_type,
t.no_of_accommodations,
t.min_price
FROM Resort r
INNER JOIN Resort_Type rt
ON rt.resort_type_id = r.resort_type_id
LEFT JOIN(
SELECT
COUNT(*) AS no_of_accommodations,
MIN(cost_per_night) AS min_price
FROM Accommodations
GROUP BY resort_id
)t
ON t.resort_id = r.resort_id