sql - Group By子句SQL中不同条件的比率
问题描述
我有一个包含三列 a、b、c 的表 t。对于 c 中的每个类别,我想计算 b = 1 的 a 的数量超过 b = 2 的 a 的数量。一些伪代码就像:(mysql)
select count(distinct a) where b = 1 / count(distinct a) where b = 2
from t
group by c
但这在 SQL 中不起作用,因为条件 'where' 不能为子句组中的 c 中的每个类别添加 c。
解决方案
您可以使用条件聚合:
select count(distinct case when b = 1 then a end) / count(distinct case when b = 2 then a end)
from t
group by c;
您没有提及您的数据库,但有些人会进行整数除法——这可能会导致意外截断。对于非整数除法,您可能需要 a* 1.0 /
而不是to。/
推荐阅读
- python - 如何在写入 Excel 时格式化数据框
- android - Dagger -Android 中构造函数注入和@Provides 的区别,举个简单的例子
- php - Symfony 5 如何为 argon2 存储盐?
- sql - SQL Server内部连接查询从多对多关系表
- jq - 使用 |= update-assignment 时 jq 管道中间需要身份运算符
- django - 有比这个更短/更简单的查询吗?
- tcp - TCP 上的类 GATT 协议
- javascript - 如何显示列表
使用 v-for 方法? - html - 通过引导程序获取中间的卡盒
- c++ - 通过更改模板之一将其更改为 muliset 后,我可以在 PBDS 有序集上使用计数功能吗
小于等于