SQL分为2列

时间:2016-11-26 19:06:55

标签: sql sql-server

作为任务的一部分,我必须为航空公司开发数据库并对其应用一些查询。 提到的查询之一是在每个航班实例中具有占用率(意味着在某个航班发生时)。 我的表格如下:

  • 飞机(serial_number,name,maker,op_start_date,op_end_date,model_name(外键)
  • 模型(name,number_rows,is_narrow,is_wide)
  • Narrow_Body(model_name,seats_left,seats_right) - 具有2个席位的模型的子类
  • Wide_Body(model_name,seats_left,seats_center,seats_right) - 具有3个席位的模型的子类
  • 腿(id,flight_code,order,departure_time,arrival_time,airport_origin,airport_destination,airplane_serial_number(外键))
  • Leg_Instances(id,flight_code,leg_id,eff_departure_time,eff_arrival_time,date)
  • Fly_In(passenger_id,flight_code,leg_instance_id,seat_type,flight_fare,leg_fare) - 收集在某个航班上飞行的乘客的信息及其相关信息

我有其他表,但在这种情况下,只有这些会影响有问题的查询。

为了得到结果,我应用了以下代码:

DECLARE @number_of_seats TABLE (airplane_serial_number varchar(50), number_seats int);
DECLARE @rate_of_occupancy TABLE (leg_instance varchar(50), airplane_serial_number varchar(50), seats_occupied int, number_seats int, occupancy_rate decimal(5,5));

INSERT INTO @number_of_seats SELECT serial_number, number_rows*(seats_left+seats_center+seats_right) FROM Airplanes JOIN Models ON Airplanes.model_name=Models.name JOIN Wide_Body ON Models.name=Wide_Body.model_name WHERE is_wide='Y'
                         UNION
                         SELECT serial_number, number_rows*(seats_left+seats_right) FROM Airplanes JOIN Models ON Airplanes.model_name=Models.name JOIN Narrow_Body ON Models.name=Narrow_Body.model_name WHERE is_narrow='Y';

INSERT INTO @rate_of_occupancy SELECT Leg_Instances.id, t1.airplane_serial_number, COUNT(passenger_id), number_seats, COUNT(passenger_id)/number_seats
FROM @number_of_seats t1 JOIN Legs ON t1.airplane_serial_number=Legs.airplane_serial_number JOIN Leg_Instances ON Legs.id=leg_id JOIN Fly_In ON Leg_Instances.id=leg_instance_id
GROUP BY Leg_Instances.id, t1.airplane_serial_number, number_seats;

SELECT * 
FROM @rate_of_occupancy

只有rate_of_occupancy的最后一栏我试图获得与总座位相关的占用席位率(occupied_seats / total_seats)。但是,获得的结果可以在以下链接中找到

http://imgur.com/0HsAO4w

任何人都可以给我任何澄清,为什么每个例子的费率为0?

0 个答案:

没有答案