我有两个桌子 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
答案 0 :(得分:0)
由于表Traffic
具有2个机场的外键,如fromAirport和ToAirport,并且列为可空值,因此请尝试使用LEFT JOIN
并使用COUNT()
函数,而不要使用SUM()
需要landings
,takeoffs
的总量:
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