如何为给定问题构建 SQL 查询?

时间:2021-06-25 14:36:56

标签: sql

我有 2 个需要 SQL 查询的 SQL 问题。

表 - 预订 enter image description here

表 - 冒险 enter image description here

表 - 游客 enter image description here

表格 - 位置 enter image description here

Query1:显示预订了所有类型冒险活动的游客的TourIdTourNa我和电子邮件。 (提示:使用联接的概念)。

我的尝试:

Select DISTINCT T.TourId, T.TourName, T.Email 
From Tourist T 
INNER JOIN Booking B ON B.TourId = T.TourId 
INNER JOIN Location L ON L.LocId = B.Loc 
INNER JOIN Adventure A ON A.AdvId = L.AdvId 
    AND A.AdvType in (Select DISTINCT AdvType From Adventure)

查询 2:对于每个预订,确定预订金额大于该位置所有预订的平均预订金额的位置。显示已识别位置的LocIdLocName评级。 (提示:使用子查询的概念)

我的尝试:

Select B.Loc, L.LocName, L.Rating 
From Booking B 
INNER JOIN Location L ON B.Loc = L.LocId 
    AND BookingAmount > (Select AVG(B.BookingAmount) from Booking B Group By B.Loc)

2 个答案:

答案 0 :(得分:1)

查询 1:

select distinct tourid,tourname,email from tourist, booking, location
where 1=1
    and tourist.tourid = booking.tourid
    and booking.locid = location.locid
    and location.advid = adventure.advid
    and adventure.advtype = 'A'

查询 2:

select locid,locname,rating
from location
where locid in (select booking.locid from booking, (select 
b.bookid,b.loc,avg(b.bookingamount) as avg_ba from booking b group by 
b.bookid,b.loc) aa
where booking.bookid = aa.bookid and booking.loc = aa.loc and 
booking.bookingamount > aa.avg_ba)
        

注意:如果是任何生产服务器的数据库设计,我必须说它需要尽快更改。 另一个注意事项:请不要使用图片作为参考。从图片中获取信息非常困难

答案 1 :(得分:1)

查询 1:-

Select DISTINCT T.TourId, T.TourName, T.Email 
From Tourist T 
INNER JOIN Booking B ON B.TourId = T.TourId 
INNER JOIN Location L ON L.LocId = B.Loc 
INNER JOIN Adventure A ON A.AdvId = L.AdvId 
    WHERE A.AdvType='A' AND A.AdvType='G' AND A.AdvType='W';

查询 2:-

Select B.Loc, L.LocName, L.Rating 
From Booking B 
INNER JOIN Location L ON B.Loc = L.LocId 
    WHERE B.BookingAmount > (Select AVG(B.BookingAmount) from Booking B Group By B.Loc);
相关问题