2

我目前有这个查询,它按降序选择最高的“拾取数量”。我只需要过滤前 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;

谢谢你的帮助!

4

2 回答 2

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

您也可以使用排名函数,但考虑到这一点相对简单,我不确定我是否会这样做。

于 2012-11-08T13:45:35.280 回答
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 行没有排序的行,然后对它们进行排序(请在评论 Andrew 的回复时通知这一点,我没有添加评论的权利)。

于 2014-04-14T14:03:32.560 回答