首页 > 解决方案 > 同一查询中的多个计数

问题描述

我有这张表,我想统计相同类型的订单数量,以及所有订单的数量,如下

ord_id type  
1      A
2      B
3      A
4      C

这是结果:

TYPE COUNT  TOTAL
A    2      4
B    1      4
C    1      4

其中 count 列是基于其类型的订单数,total 是总订单数。

这是我的代码:

SELECT type, COUNT(*)
FROM  
  table
where type = 'A'

Union

SELECT type, COUNT(*)
FROM  
  table
where type = 'b';

标签: sqloraclegroup-bycountwindow-functions

解决方案


使用聚合和窗口函数:

select 
    type,
    count(*) cnt,
    sum(count(*)) over() total
from mytable
group by type

推荐阅读