同一查询中的多个计数

n6lpvg4x  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(317)

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

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';
webghufk

webghufk1#

使用聚合和窗口函数:

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

相关问题