我想知道我是否可以在这个SQL查询上获得一些帮助。这是我失败后现在想要学习的测试。我花了很多时间在它上面,看了sql上的教程,但我仍然不知道如何编写它...
有2个表(航班,Occup_flights),包含航班信息,任务是:写一个查询,列出接下来7天的航班列表,并显示航班,可用座位数,占用数量座位和占用座位的百分比。
FLIGHTS:
FLIGHT ID_COMPANY DATE ORIGIN DESTINATION PLACES
1003 D3 20/01/2006 MADRID LONDRES 40
1007 AF 20/01/2006 PARIS MALAGA 12
1003 15 30/01/2006 MADRID LONDRES 20
1007 AF 30/01/2006 PARIS MALAGA 17
(地点显示每个航班提供的地点数量)
OCCUPATION_FLIGHTS:
FLIGHT ID_COMPANY DATE PASSENGER SEAT
1003 IB 20/01/2006 07345128H 01V
1003 IB 20/01/2006 1013456213 01P
1003 IB 20/01/2006 08124356C 02V
1003 IB 20/01/2006 57176355K 02P
1007 AF 20/01/2006 27365138A
1003 IB 30/01/2006 734512811 01V
1003 IB 30/01/2006 1013456213 02V
1003 IB 30/01/2006 57176355K
(当SEAT为空时,表示某人尚未签发机票)。 TEST DATA 我想要获得一些可用的座位我应该总结每个航班和日期乘客不是空的情况并从地方提取。 所以我开始喜欢smth:
SELECT
f.flight,
f.places - (SELECT (CASE WHEN of.passanger IS NOT NULL THEN 1 ELSE 0 END)
FROM occupation_flights AS of GROUP BY of.flight, of.date) AS available,
f.places - (SELECT (CASE WHEN of.passanger IS NULL THEN 1 ELSE 0 END) FROM occupation_flights AS of GROUP BY of.flight, of.date) AS occupied,
100.0 * ((f.places - (SELECT (CASE WHEN of.passanger IS NOT NULL THEN 1 ELSE 0 END) FROM occupation_flights AS of GROUP BY of.flight, of.date)) / f.places AS %occupied
FROM flights AS f
JOIN occupation_flights AS of ON f.flight=of.flight
WHERE f.date BETWEEN DateAdd(DD,-7,GETDATE() ) and GETDATE()
GROUP BY f.flight
但它没有完成,因为我真的不明白如何让他同时按航班和日期分组计算,因为有相同航班号但是在不同日期的航班。我也无法访问表,测试是在纸上,并表明你知道如何编写SQL查询。 对任何见解都会非常感激! 非常感谢提前!
答案 0 :(得分:1)
Mysql符合: SQLFIDDLE
SELECT f.flight,f.mydate,f.places - count(of.seat) as available_seats,
count(of.seat) as occupied,
count(of.seat)/f.places * 100 as percentage_occupied
FROM flights f
JOIN occupation_flights of
ON f.flight = of.flight AND f.mydate = of.mydate
WHERE of.mydate BETWEEN DATE_ADD(CURDATE(), INTERVAL -7 DAY)AND CURDATE()
group by f.flight, f.mydate
答案 1 :(得分:0)
select t1.flight,
t1.date,
t1.places,
t3.c,
t1.places-IFNULL(t3.c, 0) as empty
from flights t1
left join(
select count(t2.seat) as c, t2.flight, t2.date
from occupation_flights t2
where seat is not null
group by flight, date
) t3
on t1.flight= t3.flight and t1.date= t3.date
,这是结果
PS。在我的代码中,使用了一个MySql函数IFNULL(),它应该被另一个数据库工具中的其他类似函数替换。
答案 2 :(得分:0)
SELECT
f.flight, f.mydate, f.id_company, origin, destination,
places, (places - COALESCE(t.ocupped_seats, 0)) as available_places,
IFNULL(t.ocupped_seats, 0) as ocupped_places,
CONCAT(ROUND(COALESCE(places/COALESCE(t.ocupped_seats, 0), 0), 2), '%') as percentage
FROM
flights as f
LEFT JOIN
(SELECT
flight, mydate,id_company, COUNT(seat) as ocupped_seats
FROM
occupation_flights
WHERE
seat IS NOT NULL
GROUP BY
flight, mydate) as t
ON
f.flight = t.flight AND f.mydate LIKE t.mydate
WHERE
f.mydate BETWEEN CURDATE() AND CURDATE()+7
DEMO(感谢Jeremy C.用于构建架构,Strawberry用于COALLESCE
函数)
结果: