sql - 同一查询中的多个计数
问题描述
我有这张表,我想统计相同类型的订单数量,以及所有订单的数量,如下
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';
解决方案
使用聚合和窗口函数:
select
type,
count(*) cnt,
sum(count(*)) over() total
from mytable
group by type
推荐阅读
- c++ - 具有特殊情况的 C++ 动态返回类型
- css - 组元素的转换转换属性在 Firefox 中不起作用
- typescript - react-native useRoute hook:“对象”类型上不存在属性“.....”
- java - javax.persistence.PersistenceException:org.hibernate.HibernateException:HHH000142:字节码增强失败:echosign.agreement.Participation
- operators - 谁发明了三元 (elvis ?:) 运算符?
- databricks - Databricks 笔记本%运行相对路径,不适用于 3 级深度
- python - 使用不同的配置运行同一脚本的两个不同实例
- python - Python - 用另一个字典更新字典的值
- tensorflow2.0 - concat使我的jupyter笔记本崩溃后的Tensorflow滚动张量
- npm - 我应该怎么做才能用 sveltekit 和 netify-cms 解决这个上游依赖问题