首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SQL中的百分比计算

SQL中的百分比计算
EN

Stack Overflow用户
提问于 2021-06-23 16:36:12
回答 1查看 36关注 0票数 0

我在一张桌子上放了几辆车,以及它们出来的那一年,我试着计算出属于以下四个年龄组的汽车的百分比: 0-4,5-9,10-19,20+。

我试着用三种不同的方式做这件事:

1.

代码语言:javascript
运行
复制
Select (Select(Count(*) from public."Vehicles".first_year where first_year between 2018 and 2021)* 100 / (Select Count(*) From public."Vehicles")) as Percentage
From public."Vehicles";

我发现了一个错误:

代码语言:javascript
运行
复制
ERROR:  syntax error at or near "from"
LINE 1: Select (Select(Count(*) from public."Vehicles".first_year wh...

代码语言:javascript
运行
复制
SELECT SUM(CASE WHEN public."Vehicles".first_year > 2017 AND public."Vehicles".first_year < 2022 THEN 1 ELSE 0 END) AS ['4 and under'],`
        SUM(CASE WHEN public."Vehicles".first_year > 2012 AND public."Vehicles".first_year < 2018 THEN 1 ELSE 0 END) AS ['5-9'],
        SUM(CASE WHEN public."Vehicles".first_year > 2002 AND public."Vehicles".first_year < 2013 THEN 1 ELSE 0 END) AS ['10-19'],
        SUM(CASE WHEN public."Vehicles".first_year < 2003 THEN 1 ELSE 0 END) AS ['20 and older']
 FROM public."Vehicles";

我发现了一个错误:

代码语言:javascript
运行
复制
ERROR:  syntax error at or near "["
LINE 1: ...Vehicles".first_year < 2022 THEN 1 ELSE 0 END) AS ['4 and un...

代码语言:javascript
运行
复制
ROUND(CAST(((Count(*) from public."Vehicles".first_year where first_year between 2018 and 2021) * 100.0 / (Select Count(*) From public."Vehicles")) AS FLOAT), 2) AS Percentage;

我发现了一个错误:

代码语言:javascript
运行
复制
ERROR:  syntax error at or near "["
LINE 1: ...Vehicles".first_year < 2022 THEN 1 ELSE 0 END) AS ['4 and un...

对我能做什么有什么想法吗?我用的是pgadmin4和PostgreSQL 13

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-23 16:40:24

给你的专栏更合理的名字!然后进行计算:

代码语言:javascript
运行
复制
SELECT AVG(CASE WHEN v.first_year > 2017 AND v.first_year < 2022 THEN 1.0 ELSE 0 END) AS avg_4_and_under,
       AVG(CASE WHEN v.first_year > 2012 AND v.first_year < 2018 THEN 1.0 ELSE 0 END) AS avg_5_9,
       AVG(CASE WHEN v.first_year > 2002 AND v.first_year < 2013 THEN 1.0 ELSE 0 END) AS avg_10_19,
       AVG(CASE WHEN v.first_year < 2003 THEN 1.0 ELSE 0 END) AS avg_20_and_older
FROM public."Vehicles" v;

请注意对查询的更改:

  • 列别名是简单的标识符,不需要转义。高度recommended.
  • The计算使用AVG()来获取比率,而不是对计数使用SUM()。这就是你想要的问题。
  • 表别名使查询更易于编写和阅读。因此,v.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68103878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档