【问题标题】:SQL / Postgresql count multiple columns with conditionsSQL / Postgresql 用条件计算多列
【发布时间】: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


【解决方案1】:

您可以取消透视和聚合。一种方法是:

select name,
       sum(case when feature and gender = 'male' then 1 else 0 end) as num_male,
       sum(case when feature and gender = 'female' then 1 else 0 end) as num_female
from ((select 'a_feature' as name, a_feature as feature, gender
       from t
      ) union all
      (select 'b_feature' as name, b_feature, gender
       from t
      ) union all
      . . .
     ) f
group by name;

在 Postgres 中,您可以使用横向连接进行反透视:

select name,
       sum(case when feature and gender = 'male' then 1 else 0 end) as num_male,
       sum(case when feature and gender = 'female' then 1 else 0 end) as num_female
from t cross join lateral
     (values ('a_feature', a_feature),
             ('b_feature', b_feature),
             . . .
     ) v(name, feature)
group by name;

如果您不愿意全部输入,可以使用information_schema.columns 生成values() 的列表。

编辑:

您可以使用以下方式构造values 子句:

select string_agg('(''' || column_name || ''', column_name)', ', ') 
from information_schema.columns
where table_name = ?

【讨论】:

  • 谢谢 Gordon,这就是我要找的东西!
  • 亲爱的 Gordon,您能否起草一个如何使用 information_schema.columns 获取动态查询的示例?
猜你喜欢
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2017-12-15
  • 2015-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多