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

Sql 添加总计行并转换为百分比,sql,postgresql,Sql,Postgresql,我有一个数据库,里面有人们的工作条件和邻居的信息 我必须以百分比显示信息图表,如下所示: Neighbourhood Total Employed Unemployed Inactive Total 100 50 25 25 1 100 45 30 25 2 100 55 20 25 为此,到目前为止我编写的代

我有一个数据库,里面有人们的工作条件和邻居的信息

我必须以百分比显示信息图表,如下所示:

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
该代码的输出为(绝对值是由数字组成的,它们不会产生上述百分比):

因此,我必须将绝对数转换为百分比,并将总行相加(将邻里的值相加),但我所有的努力都失败了。我无法解决如何添加总行数,也无法解决如何计算每个街区的总行数以计算百分比

我两周前才开始学习SQL,因此,对于给您带来的不便,我深表歉意。我尽我最大的努力保持它的简单(在我的数据库中有15个街区,如果它们用数字标记就可以了)


谢谢

您需要将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

您可以使用分组集添加总行数:

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()

我收到一条错误消息:sintax对整数“all”无效当我运行union上的代码时,邻域列显示为“未知”。对于并集下面的代码,neighbourth是整数(也就是说,hoods是用数字命名的),不能在同一列上有整数和字符串,因此需要将neighbouroud转换为字符串
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;