postgresql - postgres中的子查询错误

标签 postgresql

我有下表,customers_categorization:

customer__id    visit_month    cust_type
2170809793      0              lagger
2170809793      10             retained
2170809793      11             retained
2170809793      12             lagger
2170809793      17             lagger
2170809793      23             retained
2170809793      24             lost
2174188545      0              lost

我正在尝试在 Postgresql 中编写一个 SQL 查询,我想在其中找到按月返回的客户比例:

这是我目前所拥有的:

select visit_month,
       count(select customer__id from customers_categorization where cust_type=’retained’)/count(customer__id) as retention_rate
    from customers_categorization
    group by 1;

我不断在“select”或“select”附近收到“语法错误”。我不确定为什么这不起作用。postgresql 是否不接受带有 select 语句的子查询?

任何帮助都会很棒!

最佳答案

使用 count()filter 的语法:

select
    visit_month,
    count(customer__id) filter (where cust_type = 'retained') /
        count(customer__id) as retention_rate
from customers_categorization
group by 1;

或使用大小写:

select
    visit_month,
    count(case when cust_type = 'retained' then customer__id end) /
        count(customer__id) as retention_rate
from customers_categorization
group by 1; 

关于postgresql - postgres中的子查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50861780/

相关文章:

ruby-on-rails - 如何使用 ActiveRecord 访问 Postgres 列默认值?

sql - 'union' 处或附近的 PostgreSQL 语法错误

eclipse - 是否可以调试 PL/Java(最好从 Eclipse 调试)?

postgresql - 通过在 postgresql 上索引时间戳列来加快搜索速度?

java - 组合 tomcat 和 postgres 时 Docker 镜像不运行

sql - 如何进行 Sequelize 查询以获取一年中日期范围不可知的项目?

c# - 无法在 "Portuguese"数据库上使用 npgsql 选择某些行

python - Django中不区分大小写的唯一模型字段?

bash - 如何使用 shell 脚本判断 postgres 数据库表是否存在

postgresql - Postgres 不知道在哪里可以找到服务器配置文件。 "brew install postgresql"之后