0

从数据库(Postgresql)中,我想获得具有特定条件的库存项目每月(所有月份)的百分比。所以整个月的总和是 100%,每个条件都是其中的一个百分比。我正在尝试各种“分区依据”查询,但我完全无法做到。

在示例中,将有一个额外的列,并且在每一行上都会有该月的百分比。所以第一行的新列的值是 25/506*100。

现在我有并且工作的是:

select to_char(created_at, 'YYYY-MM') as maand, count(si.id) as aantal,
case
    when condition_id=1 then 'Nieuw'
    when condition_id=2 then 'Als nieuw'
    when condition_id=3 then 'Goed'
    when condition_id=4 then 'Redelijk'
    when condition_id=5 then 'Matig'
    else 'Onbepaald'
end
from stock_items si
group by maand, condition_id
order by maand desc, condition_id asc
曼德 肛门 案子 新专栏
2022-01 25 25/506*100
2022-01 234 新的 234/506*100
2022-01 127 去了 127/506*100
2022-01 16 雷德莱克 16/506*100
2022-01 104 马蒂格 104/506*100
2021-12 456 其他月份

我希望一切都清楚。谢谢!

4

2 回答 2

0

只需用 CTE 扭曲它。

with a as (
    select to_char(created_at, 'YYYY-MM') as maand, count(si.id) as aantal,
    case
        when condition_id=1 then 'Nieuw'
        when condition_id=2 then 'Als nieuw'
        when condition_id=3 then 'Goed'
        when condition_id=4 then 'Redelijk'
        when condition_id=5 then 'Matig'
        else 'Onbepaald'
    end as case
    from stock_items si
    group by maand, condition_id
    order by maand desc, condition_id asc)
select a.*, aantal * 100 / sum(aantal) over (PARTITION BY maand)   as anntal_rate from a;

/* 一些字符,所以编辑被接受 */

于 2022-01-05T15:29:26.467 回答
0

我得到了我想要的。意识到我想要它有点不同,但这是我问题的答案。

select
    to_char(created_at, 'YYYY-MM') as maand, 
    count(id) as aantal,
    round((count(id) / (sum(count(id)) over (partition by to_char(created_at, 'YYYY-MM'))) * 100), 2) as percentage,
case
    when condition_id=1 then 'Nieuw'
    when condition_id=2 then 'Als nieuw'
    when condition_id=3 then 'Goed'
    when condition_id=4 then 'Redelijk'
    when condition_id=5 then 'Matig'
    else 'Onbepaald'
end
from stock_items
group by maand, condition_id
order by maand desc, condition_id asc
于 2022-01-11T15:44:24.977 回答