postgresql 查询,用于根据字段 - customerId 生成有序交易编号的报告



我在postgresql db中有一个客户事务表,其中包含以下列:

transactionId (primary)| customerId(int8)| transactionDate (timestamp)
1                        2                 2020-02-14
2                        3                 2020-03-08 
3                        1                 2020-02-06 //ignore
4                        2                 2020-02-10 // ignore
5                        2                 2020-03-24
6                        2                 2020-03-25
7                        2                 2020-02-12 //ignore (date < 13/02/2020)

我需要生成下面的报告,其中包含:

  1. 自 2020 年 2 月 13 日以来他们完成的每笔交易的时间戳分为"交易 1"、"交易 2"等
  2. 记录还应包括客户 ID。

如何生成查询以生成如下所示的报告?

CustomerId| TransactionNo | TransactionDate
2            1               2020-02-14
2            2               2020-03-24
2            3               2020-03-25
3            1               2020-03-08
select
customerId,
transactionDate
from myTable where transactionDate > '2020-02-13'
order by
customerId, transactionDate

如何添加事务编号,例如 1,2,3?

窗口函数可以帮助您实现这种格式的重新排序的交易编号

SELECT 
customerId, 
rank() OVER (PARTITION BY customerId ORDER BY transactionDate) as transactionNo,
transactionDate 
FROM 
myTable 
WHERE 
transactionDate > '2020-02-13' 
ORDER BY
customerId, transactionDate

排名函数将提供一组有序数字,即分区上的 1,2,3(即逻辑分组依据,您仍将在数据集中拥有每条记录(customerId 并按事务日期排序。

从而提供所需的结果

CustomerId| TransactionNo | TransactionDate
2            1               2020-02-14
2            2               2020-03-24
2            3               2020-03-25
3            1               2020-03-08

最新更新