sql - 过去几个月在 SQL 中花费的总量

标签 sql postgresql

我有这张表(这是示例,原始表大约有 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/

相关文章:

ios - 如何在 Swift 中使用 "IN"谓词来执行 ckQuery?

mysql - SQL Select 语句比较错误值

java - 如何将 postgresql 数据库连接到 Maven 项目?

sql - gorm 是否用逻辑 OR 解释结构体的内容?

SQL Server Management Studio 2012 挂起

sql - 一次更新多行

python - 在 Python 中跨进程共享与 postgres 数据库的连接

postgresql - 没有密码的用户连接到Postgres DB

sql - 设计可以引用多个其他表的数据库表

sql - 如何在 PostgreSQL 中找到 IP 对的最高使用率?