将具有多个可空外键的两个表连接起来

时间:2019-03-05 08:00:14

标签: sql sql-server

我有两个桌子 1)机场 2)交通(具有2个机场外键,分别为fromAirport和ToAirport) 在“交通”表中,从机场出发的时间为空,而到飞机场的某个时间 我正在收集运动的统计信息,但是由于Null值,我的统计信息不准确。 这是我的查询。

SELECT tr .Status,AL.Airline,A.City,
 SUM(ISNULL(Landings,0)) As Landings,  
 SUM(ISNULL(TakeOff,0)) As TakeOffs,  
 SUM(ISNULL(Landings,0) + ISNULL(TakeOff,0)) As Total_Movements  
 FROM dbo.Traffic tr 
 Inner Join   dbo.Airlines AL On tr.OPAirline = al.ID 
 INNER JOIN Airports A ON A.ID=COALESCE(tr.fromAirport, tr.ToAirport)
 WHERE (Date Between '01-Dec-2018' AND '31-Dec-2018') AND (tr.Status='Schedule')  
 GROUP By tr.Status,AL.Airline,COALESCE(tr.fromAirport, tr.ToAirport), A.City
 Order By tr.Status,AL.Airline

我得到的结果缺少一些动作,如果我检查每日的基本动作,则着陆和起飞大致相等。 如何通过丢失值来获得相同样式的准确结果?

Status      Airline     City    Landings    TakeOffs    Total_Movements
--------    --------    ------  ---------   ----------  ---------------
Schedule    ABC         City1   20          14          34
Schedule    CDE         City2   11          11          22
Schedule    ABCDEF      City3   18          22          40
Schedule    AFGH        City4   12          14          26

1 个答案:

答案 0 :(得分:0)

由于表Traffic具有2个机场的外键,如fromAirport和ToAirport,并且列为可空值,因此请尝试使用LEFT JOIN并使用COUNT()函数,而不要使用SUM()需要landingstakeoffs的总量:

 SELECT 
   tr.Status
 , AL.Airline
 , A.City
 , SUM(ISNULL(Landings,0)) As Landings
 , SUM(ISNULL(TakeOff,0)) As TakeOffs  
 , SUM(ISNULL(Landings,0) + ISNULL(TakeOff,0)) As Total_Movements  
 FROM dbo.Traffic tr 
 LEFT Join   dbo.Airlines AL On tr.OPAirline = al.ID 
 LEFT JOIN Airports A ON A.ID=COALESCE(tr.fromAirport, tr.ToAirport)
 WHERE (Date Between '01-Dec-2018' AND '31-Dec-2018') AND tr.Status='Schedule')  
 GROUP By tr.Status
       , AL.Airline
       , A.City
       , Landings
       , TakeOff
 Order By tr.Status,AL.Airline