假设我们有一个accounts表以及已经给出的值

我想找到帐户数量第二高的帐户类型。在这种情况下,result应为'FD'。如果它们是第二高计数的争用,我需要在结果中包含所有这些类型。
我不知道该怎么做。我在表格中找到了许多找到第二高价值的帖子,比如薪水。但不是第二高的COUNT。
发布于 2015-11-22 09:13:51
这可以使用cte来完成。第一步是获取每种类型的计数。然后使用dense_rank (在平局的情况下获得具有相同计数的多个行),以根据计数按类型获得行的排名。最后,选择排名第二的行。
with counts as (
select type, count(*) cnt
from yourtable
group by type)
, ranks as (
select type, dense_rank() over(order by cnt desc) rnk
from counts)
select type
from ranks
where rnk = 2;发布于 2015-11-22 11:21:43
一种选择是使用row_number() (或dense_rank(),这取决于"second“在有关联时是什么意思):
select a.*
from (select a.type, count(*) as cnt,
row_number() over (order by count(*) desc) as seqnum
from accounta a
group by a.type
) a
where seqnum = 2;在Oracle 12c+中,您可以使用offset/fetch
select a.type, count(*) as cnt
from accounta a
group by a.type
order by count(*) desc
offset 1
fetch first 1 row onlyhttps://stackoverflow.com/questions/33850530
复制相似问题