postgres中子查询出错

时间:2018-06-14 16:09:00

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

我在"选择"处或附近不断收到#34;语法错误。我不知道为什么这不起作用。 postgresql不接受带有select语句的子查询吗?

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

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;

case

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;