我想做什么:我有一张桌子," band_style" with schema(band_id,style)。 一个band_id可能会多次出现,以不同的样式列出。 我想要带有SECOND MOST数量的乐队ID的band_id,NUM(其中NUM是乐队的不同风格的数量)的所有行。
我在这个问题上花了好几个小时 - 几乎没有什么工作。
这是我有多远。表(数据)成功计算样式小于波段样式最大值的所有波段。现在,我需要具有结果表的最大NUM的所有行。这将为我带来第二多款式的乐队。
但是,这个最终结果似乎忽略了MAX函数,只是按原样返回表(数据)。有人可以提供一些见解/工作方法吗?我有超过20次尝试此查询,这是最接近的。
在Oracle上使用SQL * PLUS
WITH data AS (
SELECT band_id, COUNT(*) AS NUM FROM band_style GROUP BY band_id HAVING COUNT(*) <
(SELECT MAX(c) FROM
(SELECT COUNT(band_id) AS c
FROM band_style
GROUP BY band_id)))
SELECT data.band_id, data.NUM FROM data
INNER JOIN ( SELECT band_id m, MAX(NUM) n
FROM data GROUP BY band_id
) t
ON t.m = data.band_id
AND t.n = data.NUM;
答案 0 :(得分:2)
这样的东西......基于你帖子下的评论,你正在寻找DENSE_RANK()
select band_id
from ( select band_id, dense_rank() over (order by count(style) desc) as drk
from band_style
group by band_id
)
where drk = 2;
答案 1 :(得分:1)
我会使用一个窗口函数(在这种情况下是RANK()) - 这对于找到&#39; n&#39;在一组中排名。
SELECT DISTINCT bs.band_id
FROM band_style bs
WHERE EXISTS (
SELECT NULL
FROM (
SELECT
bs2.band_id,
bs2.num,
RANK() OVER (ORDER BY bs2.num) AS numrank
FROM (
SELECT bs1.band_id, COUNT(*) as num
FROM band_style bs1
GROUP BY bs1.band_id ) bs2 ) bs3
WHERE bs.band_id = bs3.band_id
AND bs3.numrank = 2 )