簡體   English   中英

postgresql 查詢生成多列報告

[英]postgresql query to generate report with multiple columns

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

客戶第一次開始的時間,總交易量,每周頻率,最近一次? 並且報告應僅考慮(包含)最近 3 個月的記錄。

試試下面的,這里是演示

with cte as
(
  select
    *,
    count(*) over (partition by customerId) as totalTransactions,
    1 + floor((extract(day from transactionDate) - 1) / 7) as transactionsWeek
  from myTable
  where transactionDate >= '2020-01-01'
  and transactionDate <= '2020-03-31'
)

select
  customerId,
  min(transactionDate) as firstTransaction,
  max(totalTransactions) as totalTransactions,
  max(transactionDate) as recentTransactions,
  (ceil(avg(totalTransactions)/count(distinct transactionsWeek))::int) as "Transactions/Week"
from cte
group by
    customerId
order by
  customerId

Output:

| customerid | firsttransaction         | totaltransactions | recenttransactions       | Transactions/Week |
| ---------- | ------------------------ | ----------------- | ------------------------ | ----------------- |
| 1          | 2020-02-06               | 1                 | 2020-02-06               | 1                 |
| 2          | 2020-02-13               | 3                 | 2020-03-24               | 2                 |
| 3          | 2020-01-08               | 1                 | 2020-01-08               | 1                 |

在過去三個月中,您還可以在where條件下使用以下

transactionDate >  CURRENT_DATE - INTERVAL '3 months'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM