首页 > 解决方案 > 编写单个 SQL 查询以计算具有“真”条件的多个布尔列的计数

问题描述

如何在一个 SQL 查询中写入多个计数。

例如,我想要一个查询中的所有布尔功能计数器,而不是下面的所有查询。

select count(feature1) from my_table where feature1 = True
select count(feature2) from my_table where feature2 = True
select count(feature3) from my_table where feature3 = True

标签: sqlsql-server

解决方案


使用如下条件聚合

select 
sum(case when feature1= 'True'  then 1 else 0 end), 
sum(case when feature2= 'True'  then 1 else 0 end),
sum(case when feature3= 'True'  then 1 else 0 end) 
from my_table 

推荐阅读