PostgreSQL - SUM true-false column and group by month 给我一个百分比

PostgreSQL - SUM true-false column & group by month giving me a percentage

我有一个 table 和我已经过滤的一些其他数据。 首先我想知道如何将输出

转换为新的 table
select A, B from Table
where B between '2020-03-01' and '2020-04-30'
order by B ASC
;

我有这样的输出:

A       B
1    12-03-2000
0    12-04-2000
1    03-02-2000
1    04-02-2000
0    02-05-2001

我的兴趣只集中在 2 个月 我想知道百分比代表每个月 true 和 false(分别)的总和

我认为您希望在列中显示每个月的真假百分比的月份。使用条件聚合:

select A,
       count(*) filter (where month(b) = 3) * 1.0 / sum(count(*)) filter (where extract(month from b) = 3) as march,
       count(*) filter (where extract(month from b) = 4) * 1.0 / sum(count(*)) filter (where month(b) = 4) as april
from Table
where B between '2020-03-01' and '2020-04-30'
group by A;