我正在寻找一个查询,可以计数新的和返回客户每月。
基本上,我有一个两年以上的客户申请贷款的数据,有些客户在那里之后第一次贷款返回后1,2,3.X个月我想要的是一个以以下格式返回结果的查询:
Month YY | New Customers | Returning Customers
Jan '16 | 6 | 0
Feb '16 | 3 | 0
Mar '16 | 2 | 3
Apr '16 | 4 | 2我表中一些我认为有用的列(Tablename:Loans)包括
customer_id的定义是一个customer_id,它在给定的一个月中首次出现在表上。返回客户是一个customer_id,它在表上随后几个月的第一个日期之后出现不止一次。
例如,: If customer_id:"2231“于1月16日首次出现在桌面上,它应被视为1月16日的新客户,如果在2个月后(即4月16日)返回,则应算作返回客户。
发布于 2018-09-27 11:39:46
像这样的事情似乎能做你想做的事:
测试设置:
create table loans
(
customer_id integer,
date_disbursed date
);
insert into loans
values
( 1, date '2016-01-01'),
( 2, date '2016-01-02'),
( 3, date '2016-01-04'),
( 4, date '2016-01-08'),
( 5, date '2016-01-12'),
( 6, date '2016-01-18'),
( 7, date '2016-02-08'),
( 8, date '2016-02-12'),
( 9, date '2016-03-18'),
(10, date '2016-03-12'),
(11, date '2016-03-18'),
( 3, date '2016-03-04'),
( 4, date '2016-03-08'),
( 5, date '2016-03-12'),
( 5, date '2016-04-12'),
(12, date '2016-04-12'),
( 5, date '2016-05-12'),
( 6, date '2016-05-18');查询:
select to_char(date_disbursed, 'yyyy-mm') as month,
count(*) filter (where new_customer) as new_customers,
count(*) filter (where recurring_customer) as returning_customers
from (
select customer_id,
date_disbursed,
date_disbursed = min(date_disbursed) over w as new_customer,
date_disbursed > min(date_disbursed) over w as recurring_customer
from loans
window w as (partition by customer_id)
) t
group by to_char(date_disbursed, 'yyyy-mm')
order by to_char(date_disbursed, 'yyyy-mm');返回
month | new_customers | returning_customers
--------+---------------+--------------------
2016-01 | 6 | 0
2016-02 | 2 | 0
2016-03 | 3 | 3
2016-04 | 1 | 1
2016-05 | 0 | 2https://stackoverflow.com/questions/52535622
复制相似问题