从SQL Count查询中选择最佳结果,包括表连接 - Oracle

时间:2012-11-08 13:42:15

标签: sql oracle join filter count

我目前有这个查询,它按降序选择最高的“拾取次数”。我需要只过滤前10行/最高数字。我怎样才能做到这一点?

我尝试在底部添加'WHERE ROWNUM< = 10',但无济于事。

SELECT customer.company_name, COUNT (item.pickup_reference) as "Number of Pickups" 
FROM customer
JOIN item ON (customer.reference_no=item.pickup_reference) 
GROUP BY customer.company_name, item.pickup_reference
ORDER BY COUNT (customer.company_name) DESC;

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

您需要对其进行子查询以使rownum正常工作。

SELECT *
FROM
(
SELECT customer.company_name, COUNT (item.pickup_reference) as "Number of Pickups" 
FROM customer
JOIN item ON (customer.reference_no=item.pickup_reference) 
GROUP BY customer.company_name, item.pickup_reference
ORDER BY COUNT (customer.company_name) DESC
) 
WHERE rownum <= 10

您也可以使用排名功能,但考虑到相对简单,我不确定是否愿意。

答案 1 :(得分:1)

使用等级的解决方案是这样的:

select customer.company_name, COUNT (item.pickup_reference) from (
    select distinct customer.company_name, COUNT (item.pickup_reference) ,
    rank() over ( order by count(item.pickup_reference) desc) rnk 
    from customer
    JOIN item ON (customer.reference_no=item.pickup_reference) 
    group by customer.company_name, item.pickup_reference
    order by COUNT (customer.company_name) )
where rnk < 10

使用'rownum'得到最高结果并没有给出预期的结果,因为它获得了10个没有ordred的第一行,然后订购它们(请在安德鲁的回复评论中通知这个,我不要没有权利添加评论。