计算表中的百分比对于同一查询给出正确和错误的答案

问题描述 投票:0回答:2

我有一张包含年份、区号的表格,每个区号有 5 个年龄组类别,人数如下。

区号 年龄组
2021 代码1 20-29 5
2021 代码2 30-39 11
2022 代码1 20-29 7
2022 代码2 30-39 5
2020 代码1 20-29 0
2020 代码2 30-39 6
2019 代码1 20-29 0
2019 代码2 30-39 0

我需要计算每个区号的每组人数占总人数的百分比,我需要的结果是:

fid 区号 年龄组 百分比
1 2021 代码1 20-29 5 31.3%
2 2021 代码2 30-39 11 68.8%
3 2022 代码1 20-29 7 58.3%
4 2022 代码2 30-39 5 41.7%
5 2020 代码1 20-29 0 0.0%
6 2020 代码2 30-39 6 100.0%
7 2019 代码1 20-29 0 0.0%
8 2019 代码2 30-39 0 0.0%

但是我得到的结果很奇怪,它部分给出了正确答案,也给出了错误答案。请参阅下面的结果。

fid 区号 年龄组 总和 测试 百分比
1 2021 代码1 20-29 5 16 1 0.0%
2 2021 代码2 30-39 11 16 1 0.0%
3 2022 代码1 20-29 7 12 1 0.0%
4 2022 代码2 30-39 5 12 1 0.0%
5 2020 代码1 20-29 0 6 1 0.0%
6 2020 代码2 30-39 6 6 1 100.0%
7 2019 代码1 20-29 0 0 0 0.0%
8 2019 代码2 30-39 0 0 0 0.0%

除 0 或 100 之外的任何百分比都会导致 0% 为了测试 Total_sum 列,我添加了测试列,其中总计为 0 给出 0,否则给出 1。效果非常好。

我正在使用以下代码:

select 
    table.fid, 
    table.year, 
    table.areacode,
    table.agegroup,
    table.persons,
    totals.total_sum,
    case
        when totals.total_sum = 0 then 0
        else 1
    end as test,
    case
        when totals.total_sum = 0 then 0
        else ((table.persons)/totals.total_sum)*100.0
    end as percent
from abc.table
join (
    select
        table.year,
        table.areacode,
        sum(table.persons) as total_sum
    from abc.table
    group by table.areacode, table.year) as totals
on table.areacode = totals.areacode and table.year=totals.year
group by table.areacode, table.fid, table.year, table.agegroup, totals.total_sum
order by totals.total_sum

我尝试查找与此类错误相关的任何内容,但不幸的是,我没有找到任何内容(也许,我使用了错误的关键字)。

有谁知道为什么会这样?我真的很感激。

sql postgresql pgadmin postgresql-15
2个回答
0
投票
SELECT t.year, 
       t.areacode, 
       t.agegroup, 
       COALESCE(t.persons, 0) AS persons, -- Replace null with 0
       total_by_year.total_persons,
       (COALESCE(t.persons, 0) / total_by_year.total_persons) * 100 AS percentage -- Replace null with 0
FROM table_name t
INNER JOIN (
    SELECT year, SUM(COALESCE(persons, 0)) AS total_persons -- Replace null with 0
    FROM table_name
    GROUP BY year
) AS total_by_year ON t.year = total_by_year.year  
ORDER BY t.year DESC

您可以尝试使用此查询。如果加上主键就好了,这样有助于排序。


0
投票

整数除法会丢弃余数。在除法完成之前,您需要将一个整数更改为浮点数。只需将常数移到前面并放在括号内即可

(100.0*table.persons/totals.total_sum)
© www.soinside.com 2019 - 2024. All rights reserved.