Sum for multiple date ranges in a single call?

前端 未结 10 1771
有刺的猬
有刺的猬 2021-02-14 10:36

I have the following query:

SELECT 
   SUM(\"balance_transactions\".\"fee\") AS sum_id 
   FROM \"balance_transactions\" 
   JOIN charges ON balance_transactions         


        
10条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-14 11:39

    Try this:

    create table timeframes (
        start_dt date,
        end_dt date
    );
    
    insert into timeframes values ('2013-12-20', '2014-01-19');
    insert into timeframes values ('2013-12-21', '2014-01-20');
    insert into timeframes values ('2013-12-22', '2014-01-21');
    insert into timeframes values ('2013-12-23', '2014-01-22');
    insert into timeframes values ('2013-12-24', '2014-01-23');
    
    SELECT 
        tf.start_date, 
        tf.end_date, 
        SUM(CASE 
            WHEN t.created BETWEEN tf.start_date AND tf.end_date THEN t.fee
            ELSE 0.00 
        END) as transaction_sum
    FROM 
        balance_transactions t
    INNER JOIN 
        charges c
    ON 
        t.source = c.balance_id 
    INNER JOIN 
        timeframes tf
    ON 
        t.created BETWEEN tf.start_date AND tf.end_date
    WHERE 
        t.account_id = 6
    AND 
        (
        t.type = 'charge' 
            AND 
        c.refunded = false 
            AND 
        c.invoice IS NOT NULL
        ) 
    GROUP BY
        tf.start_date, 
        tf.end_date
    

提交回复
热议问题