伙计我有以下问题:
select count(*) AS num_items
from desc_look
group by dept
此查询返回每个部门中的项目数。但是,我不能只获得物品数量较多的部门。
我一直试图用它来检索大部分项目的部门名称和ID
select dept, desc_up
from desc_look
where (select count(*) AS num_items
from desc_look
group by dept)
但是我一直收到错误ORA-00936而且我不知道为什么。 我知道我不能使用MAX(COUNT(*))但是有办法解决这个问题吗?
答案 0 :(得分:4)
select * from
(
select count(*) AS num_items
from desc_look
group by dept
order by count(*) desc
) tmp
WHERE ROWNUM = 1;
答案 1 :(得分:2)
此版本与juergen的版本基本相同,但使用分析函数而不是聚合(GROUP BY
)进行计数:
SELECT t.dept, t.desc_up FROM
(SELECT dept, desc_up,
COUNT(*) over (partition BY dept) dept_count
FROM desc_look
ORDER BY dept_count DESC
) t
WHERE rownum = 1
如果您使用的是Oracle 12,则不需要内联视图,因为您可以使用行限制子句(FETCH FIRST ...
):
SELECT dept, desc_up,
COUNT(*) over (partition BY dept) dept_count
FROM desc_look
ORDER BY dept_count DESC
FETCH FIRST 1 ROW ONLY
答案 2 :(得分:0)
我认为这可能会对你有所帮助
select count(*) AS num_items
from desc_look
group by dept
order by count(*) desc
limit 1
答案 3 :(得分:0)
您可以尝试这样的事情:
SELECT dept, num_items FROM (
SELECT dept, COUNT(*) AS num_items
, ROW_NUMBER() OVER ( ORDER BY COUNT(*) DESC ) AS rn
FROM desc_look
GROUP BY dept
) WHERE rn = 1;