db2 确定谁在任何30天内的消费超过了一定金额?

kwvwclae  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(147)

我有一个表,其中列出了每个客户的交易,沿着交易发生的日期和花费的金额。我想做的是获得一个在任何30天内花费3000英镑或更多的所有客户的列表。
我可以得到一个名单,谁花了£ 3 k或更多的 * 过去 * 30天使用下面的代码,但我不知道如何适应这一点,以涵盖 * 任何 * 30天期间。任何帮助将不胜感激,请!

select  *
from
        (
        select      customer_id, sum(spend) as total_spend
        from        transaction_table
        where       transaction_date between (current date - 30 days) and current date
        group by    customer_id
        )
where   total_spend >=3000
;
xzv2uavs

xzv2uavs1#

可以将SUM()与窗口函数和窗口框架30一起使用。例如:

select *
from (
  select t.*,
    sum(t.spent) over(
      partition by customer_id 
      order by julian_day(transaction_date)
      range between 30 preceding and current row
    ) as total_spend
  from transaction_table t
) x
where total_spend >= 3000

对于数据集:

CUSTOMER_ID  TRANSACTION_DATE  SPENT 
 ------------ ----------------- ----- 
 1            2021-10-01        2000  
 1            2021-10-15        1500  
 1            2021-12-01        1000  
 2            2021-11-01        2500

结果:

CUSTOMER_ID  TRANSACTION_DATE  SPENT  TOTAL_SPEND 
 ------------ ----------------- ------ ----------- 
 1            2021-10-15        1500   3500

请参阅db<>fiddle上的运行示例。

ufj5ltwl

ufj5ltwl2#

请尝试以下操作。
其思想是计算每行过去30天的SPEND运行总和。

WITH TRANSACTION_TABLE (CUSTOMER_ID, TRANSACTION_DATE, SPEND) AS
(
VALUES
  (1, DATE ('2021-01-01'), 1000)
, (1, DATE ('2021-01-31'), 2000)
--, (1, DATE ('2021-02-01'), 2000)
)
SELECT DISTINCT CUSTOMER_ID
FROM
(
SELECT 
  CUSTOMER_ID
--, TRANSACTION_DATE, SPEND
, SUM (SPEND) OVER (PARTITION BY CUSTOMER_ID ORDER BY DAYS (TRANSACTION_DATE) RANGE BETWEEN 30 PRECEDING AND CURRENT ROW) AS SPEND_RTOTAL
FROM TRANSACTION_TABLE
)
WHERE SPEND_RTOTAL >= 3000

相关问题