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

时间:2017-09-23 23:19:02

标签: sql postgresql

我有一个数据库,其中包含有关人员工作条件和社区的信息。

我必须以这样的百分比显示信息图表:

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

为此,我到目前为止所做的代码是:

   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

该代码的输出是(绝对数字组成,它们不会产生上述百分比):

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

所以,我必须以百分比形式改变absolut数字并添加Total Row(总计来自邻域的值),但我所有的努力都失败了。我无法解决如何添加Total行以及如何为每个邻域计算百分比

两周前我开始学习SQL,所以对于给您带来的任何不便,我深表歉意。我尽力保持简单(在我的数据库中有15个社区,如果他们被数字标记,那就没关系)

由于

2 个答案:

答案 0 :(得分:1)

你需要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

答案 1 :(得分:1)

您可以使用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;

如果您希望每行 中的平均值,请使用avg()而不是sum()