Sum for multiple date ranges in a single call?

前端 未结 10 1346
礼貌的吻别
礼貌的吻别 2021-02-14 11:03

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:41

    This will return all the month ranges' sum between a given date and today.

    Tuples output - SQL Fiddle

    select distinct on (s.d)
        s.d as "date",
        sum(bt.fee) over (
            partition by daterange(s.d, (s.d + interval '1 month')::date, '[]')
        ) as sum_id
    from
        balance_transactions bt
        inner join
        charges on bt.source = charges.balance_id
        right join
        (
            select d::date as d
            from generate_series (
                '2013-12-20'::date,
                current_date,
                interval '1 day'
            ) s(d)
        ) s on s.d = bt.created
    where
        bt.account_id = 6
        and bt.type = 'charge'
        and charges.refunded = false
        and charges.invoice is not null
    order by s.d
    

    Array output. Does not work on SQL Fiddle but works in my desktop.

    select array_agg(("date", sum_id)) as arr_sum_id
    from (
        select distinct on (s.d)
            s.d as "date",
            sum(bt.fee) over (
                partition by daterange(s.d, (s.d + interval '1 month')::date, '[]')
            ) as sum_id
        from
            balance_transactions bt
            inner join
            charges on bt.source = charges.balance_id
            right join
            (
                select d::date as d
                from generate_series (
                    '2013-12-20'::date,
                    current_date,
                    interval '1 day'
                ) s(d)
            ) s on s.d = bt.created
        where
            bt.account_id = 6
            and bt.type = 'charge'
            and charges.refunded = false
            and charges.invoice is not null
        order by s.d
    ) s
    

提交回复
热议问题