首页 > 解决方案 > 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。

标签: sql

解决方案


您可以使用条件聚合:

 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。/


推荐阅读