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

标签 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

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

我两周前才开始学习 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

关于sql - 添加总计行并转换为百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46385134/

相关文章:

sql - Postgres数据库设计——仪表盘功能

sql - 用另一个表中的值替换表列中的值

c# - linq to sql使用lambda连接多列

mysql - 在哪里可以找到 NetBeans 的 MySQL 路径/URL?

php - 将行从一个表复制到另一个表时出现问题

postgresql - 在 Postgres 中创建一个触发器,它将一条记录插入到另一个带有添加列的表中

SQL Azure 别名 DNS 名称

postgresql - pg_dump 和 pg_restore 跨越不同主要版本的 PostgreSQL

php - SQL 将 ORDER BY 结果作为数组返回

postgresql - 使用 PostgreSQL/PostGIS 函数设置值的 Sequelize 模型