【发布时间】:2021-09-07 00:12:06
【问题描述】:
我有一个简单的表格:
| id | gender | a_feature (bool) | b_feature (bool) | ... | xyz_feature (bool) |
|---|
我想根据性别对所有特征列求和。
| metric | male | female |
|---|---|---|
| a_feature | 345 | 3423 |
| b_feature | 65 | 143 |
| ... | ... | ... |
| xyz_feature | 133 | 5536 |
有没有一种简单的方法可以做到这一点,例如使用 information_schema。
我只找到了下面的解决方案,但这很丑:
select
'a_feature' as feature_name,
count(case a_feature and gender = 'male') as male,
count(case a_feature and gender = 'female') as female
from table
union
select
b_feature as feature_name,
count(case b_feature and gender = 'male') as male,
count(case b_feature and gender = 'female') as female
from table
.
.
.
select
xyz_feature as feature_name,
count(case xyz_feature and gender = 'male') as male,
count(case xyz_feature and gender = 'female') as female
from table
【问题讨论】:
-
用您正在使用的数据库标记您的问题。您拥有的代码在语法上也无效。
标签: sql postgresql count multiple-columns postgresql-12