简体   繁体   English

添加总计行并转换为百分比

[英]Add a Total Row and converting into percentages

I have a database with information about people's work condition and neighbourhood.我有一个包含人们工作条件和社区信息的数据库。

I have to display a chart of information in percentages like this:我必须以百分比形式显示信息图表,如下所示:

Neighbourhood Total  Employed Unemployed Inactive
Total          100     50         25        25
1              100     45         30        25
2              100     55         20        25

To do that, the code that I've made so far is:为此,我到目前为止所做的代码是:

   select neighbourhood, Count (*) as Total,
   Count(Case when (condition = 1) then 'employed' end) as employed,
   Count (case when (condition = 2) then 'unemployed' end) as unemployed,
   Count (Case when (condition =3) then 'Inactive' end) as Inactive

   from table
   group by  neighbourhood
   order by  neighbourhood

the output for that code is (the absolut numbers are made up, they dont result in the percentages above):该代码的输出是(绝对数字是组成的,它们不会导致上面的百分比):

   Neighbourhood Total  Employed Unemployed Inactive
   1              600     300        200        100
   2              450     220        159        80

So, I have to turn the absolut numbers in percentages and add the Total Row (suming the values from the neighbourhoods) but I all my efforts were a failure.因此,我必须以百分比形式转换绝对数字并添加总行(求和来自社区的值),但我所有的努力都失败了。 I can't solve how to add that Total row nor how to have that total for each neighbourhood for calculating the percentages我无法解决如何添加该 Total 行,也无法解决如何为每个社区计算百分比的总数

I started studying SQL just two weeks ago so I apologize for any inconvenience.我两周前才开始学习 SQL,因此给您带来的不便,我深表歉意。 I tried my best to keep it simple (in my database are 15 neighbourhoods and it's ok if they are labeled by numbers)我尽量保持简单(在我的数据库中有 15 个街区,如果用数字标记就可以了)

Thanks谢谢

You need to UNION to the add the total row您需要 UNION 添加总行

   select 'All' as neighbourhood, Count (*) as Total,
   Count(Case when (condition = 1) then 1 end) as employed,
   Count (case when (condition = 2) then 1 end) as unemployed,
   Count (Case when (condition =3) then 1 end) as Inactive

   from table

   UNION all

   select neighbourhood, Count (*) as Total,
   Count(Case when (condition = 1) then 1 end) as employed,
   Count (case when (condition = 2) then 1 end) as unemployed,
   Count (Case when (condition =3) then 1 end) as Inactive

   from table
   group by  neighbourhood
   order by  neighbourhood

You can add the total rows using grouping sets :您可以使用grouping sets添加总行数:

select neighbourhood, Count(*) as Total,
       sum((condition = 1)::int) as employed,
       sum((condition = 2)::int) as unemployed,
       sum((condition = 3)::int) as Inactive
from table
group by grouping sets ( (neighbourhood), () )
order by  neighbourhood;

If you want averages within each row, then use avg() rather than sum() .如果您想要每行内的平均值,请使用avg()而不是sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM