确定谁在任何 30 天内花费超过一定金额?
Identifying who spent more than a certain amount within any 30 day period?
我有一个 table,其中列出了每个客户的交易以及交易发生的日期和花费的金额。我想要做的是获取在任何 30 天内花费 3000 英镑或更多的所有客户的列表。
我可以使用下面的代码获得在最后 30 天内花费 3000 英镑或更多的人的列表,但我不确定如何调整它以涵盖 任意 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
;
您可以将 SUM()
与 window 函数和 window 帧 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 中的 运行 示例。
试试下面的方法。
这个想法是计算每行过去 30 天的 运行 支出总和。
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
我有一个 table,其中列出了每个客户的交易以及交易发生的日期和花费的金额。我想要做的是获取在任何 30 天内花费 3000 英镑或更多的所有客户的列表。
我可以使用下面的代码获得在最后 30 天内花费 3000 英镑或更多的人的列表,但我不确定如何调整它以涵盖 任意 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
;
您可以将 SUM()
与 window 函数和 window 帧 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 中的 运行 示例。
试试下面的方法。
这个想法是计算每行过去 30 天的 运行 支出总和。
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