我有下表,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/