在rownum中使用count(*)

时间:2018-10-10 23:18:13

标签: sql oracle

我想计算客户请求和订购的时间,只显示前10个输出。我使用count和rownum函数,如下所示,但是订单的计数未在代码中实现。请在下面查看我的代码,对于解决该问题的建议,我将不胜感激。谢谢。

SET SERVEROUT ON
create or replace procedure total is
begin
for a in (select customer_no, count(*) as total from orders where rownum <= 
10 group by customer_no)
loop
dbms_output.put_line('customer number '||a.customer_no|| ' total orders 
'||a.total);

end loop;
end;
/
execute total;
drop procedure total;

输出具有行数的示例

Procedure TOTAL compiled

customer number 1062 total orders 1
customer number 1054 total orders 1
customer number 1051 total orders 1
customer number 1060 total orders 1
customer number 1052 total orders 1
customer number 1059 total orders 1
customer number 1061 total orders 1
customer number 1055 total orders 1
customer number 1053 total orders 1
customer number 1058 total orders 1


PL/SQL procedure successfully completed.
Procedure TOTAL dropped.

不包含行号的输出示例:

Procedure TOTAL compiled

customer number 1098 total orders 25
customer number 1041 total orders 11
customer number 1000 total orders 18
customer number 1003 total orders 16



PL/SQL procedure successfully completed.


Procedure TOTAL dropped.

1 个答案:

答案 0 :(得分:4)

您只需要10行,而不必关心它们处于哪10个或什么顺序?

SELECT *
FROM (SELECT customer_no, count(*) AS total
      FROM orders
      GROUP BY customer_no)
WHERE rownum <= 10;

Example

(据说Oracle 12支持FETCH FIRST语法来返回给定数量的行,但是我没有任何测试方法)