我在 Oracle
中有两个表 Flight
:
-------------------------
fl_no | fl_date | fl_time
-------------------------
Passenger
:
------------------------------------
ps_id | fl_no | ps_name | ps_address
------------------------------------
现在我需要显示最多乘客的航班。但我只是无法弄清楚查询。任何人都可以帮助我吗?
答案 0 :(得分:3)
您可以使用分析函数(dense_rank
)将查询减少到一个表扫描:(以提高查询运行的速度)
select *
from (select fl_no,
num_pass,
dense_rank() over(order by num_pass desc) as rnk
from (select fl_no, count(*) as num_pass
from passenger
group by fl_no))
where rnk = 1
小提琴: http://sqlfiddle.com/#!4/7a1d1/10/0
(请注意我在1号和3号航班之间打了个小提琴;两人都有3名乘客,是所有航班中乘客数量最多的乘客)
如前所述,如果您需要从该表返回的其他字段,请加入flight
表。例如,如果您希望在每次此类航班的日期中添加您可以运行的最多乘客:
select x.*, f.fl_date
from (select fl_no,
num_pass,
dense_rank() over(order by num_pass desc) as rnk
from (select fl_no, count(*) as num_pass
from passenger
group by fl_no)) x
join flight f
on x.fl_no = f.fl_no
where rnk = 1
答案 1 :(得分:2)
我会使用order by
和rownum
执行此操作:
select *
from (select fl_no, count(*) as cnt
from passenger p
group by fl_no
order by cnt desc
) f
where rownum = 1;
虽然可以使用窗口函数,但它们看起来有点过分。
请注意,在Oracle 12+中,这可以简化为:
select fl_no, count(*) as cnt
from passenger p
group by fl_no
order by cnt desc
fetch first 1 row only;
编辑:
如果您想要所有这些航班,那么分析功能就是您的选择。这是编写这样一个查询的另一种方法(Brian已经有一个方法):
select *
from (select fl_no, count(*) as cnt, max(count(*)) over () as maxcnt
from passenger p
group by fl_no
order by cnt desc
) f
where cnt = maxcnt;