我在postgresql db中有一个客户交易表,其以下各栏
transactionId (primary)| customerId(int8)| transactionDate (timestamp)
1 2 2020-02-14
2 3 2020-01-08
3 1 2020-02-06
4 2 2020-02-13
5 2 2020-03-24
需要建立查询以创建以下报告
CustomerId| FirstTransaction| TotalTransactions| Transactions/Week| RecentTransactions
1 2020-02-06 1 1 2020-02-06
3 2020-01-08 1 1 2020-01-08
2 2020-02-13 3 2 2020-03-24
[客户最初开始时,总交易次数,每周频率,最近一次回访率?
尝试以下操作
with cte as
(
select
*,
row_number() over (partition by customerId order by transactionDate) as rnk
from yourTable
)
select
customerId,
case when rnk = 1 then transactionDate end as FirstTransaction,
count(*) over (partition by customerId) as TotalTransactions,
extract('week' from transactionDate)
case when rnk = 2 then transactionDate end as FirstTransaction as RecentTransactions
from cte
order by
customerId