需要查看子查询的合并输出

时间:2019-05-17 09:52:19

标签: sql oracle

我需要查看航班号,该航班的机票数量,该航班的工作人员(空中小姐)数量。

我可以通过2个子查询看到它们,但是看不到统一视图

        select f.flightid, count(ticketnum)  from flight f , ticket t 
        where f.actDepartDateTime is not null
        and  f.flightid=t.flightid
        group by f.flightid
        order by 1;


        select f.flightid, count(h.staffid) from flight f ,hosting h
        where f.actDepartDateTime is not null
        and   f.flightid=h.flightID 
        group by f.flightid
        order by 1;

2 个答案:

答案 0 :(得分:1)

简单的解决方案-使用相关子查询进行计数。 (无需担心多对多关系,多次加入,没有机票的航班等)。

select f.flightid, 
       (select count(*) from ticket t where f.flightid = t.flightid) as cnt_ticketnum, 
       (select count(*) from hosting h where f.flightid = h.flightID) as cnt_staffid
from flight f 
where f.actDepartDateTime is not null           
order by f.flightid

答案 1 :(得分:0)

在所有三个表中使用这样的inner join语句

    select f.flightid, 
           count( case when nvl(t.ticketnum,0)>0 then 1 end ) as cnt_ticketnum, 
           count( case when nvl(h.staffid,0)>0   then 1 end ) as cnt_staffid
      from flight f 
      join hosting h on f.flightid=h.flightID 
      join ticket t on f.flightid=t.flightid
     where f.actDepartDateTime is not null           
     group by f.flightid
     order by f.flightid;