我有这张表(这是示例,原始表大约有 800000 行):
purchase_datetime customer_id value purchase_id
2013-01-08 17:13:29 45236262 92 2526373
2013-01-03 15:42:35 45236262 16 2565373
2013-05-08 17:40:13 45236262 42 2522373
2013-03-08 09:04:52 45236262 636 2563373
2013-12-08 12:12:24 45236262 23 2505573
2013-07-08 22:35:53 35536272 73 2526423
2013-07-08 09:52:03 35536272 4 5526373
2013-010-08 16:23:29 52626262 20 2226373
...
2013-04-08 17:49:31 52626262 27 4526373
2013-12-09 20:40:53 52626262 27 4626373
现在我需要找出客户在过去 1 个月、3 个月、6 个月和 12 个月内花费的总金额(值(value))。 我不知道如何处理日期时间来选择最后几个月。
最佳答案
您可以使用条件聚合:
select customer_id,
sum(case when purchase_datetime >= current_timestamp - interval '1 month'
then value else 0
end) as amount_1month,
sum(case when purchase_datetime >= current_timestamp - interval '3 month'
then value else 0
end) as amount_3month,
sum(case when purchase_datetime >= current_timestamp - interval '6 month'
then value else 0
end) as amount_6month
. . .
关于sql - 过去几个月在 SQL 中花费的总量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44134963/