PostgreSQL查询以生成多列报告

问题描述 投票:0回答:1

我在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

[客户最初开始时,总交易次数,每周频率,最近一次回访率?

sql database postgresql postgresql-9.1 postgresql-9.3
1个回答
0
投票

尝试以下操作

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
© www.soinside.com 2019 - 2024. All rights reserved.