Sum for multiple date ranges in a single call?

前端 未结 10 1383
礼貌的吻别
礼貌的吻别 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:39

    Assuming I understand your request correctly I think what you need is something along these lines:

    SELECT "periods"."start_date", 
           "periods"."end_date", 
           SUM(CASE WHEN "balance_transactions"."created" BETWEEN "periods"."start_date" AND "periods"."end_date" THEN "balance_transactions"."fee" ELSE 0.00 END) AS period_sum
      FROM "balance_transactions" 
      JOIN charges ON balance_transactions.source = charges.balance_id 
      JOIN ( SELECT '2013-12-20'::date as start_date, '2014-01-19'::date as end_date UNION ALL
             SELECT '2013-12-21'::date as start_date, '2014-01-20'::date as end_date UNION ALL
             SELECT '2013-12-22'::date as start_date, '2014-01-21'::date as end_date UNION ALL
             SELECT '2013-12-23'::date as start_date, '2014-01-22'::date as end_date UNION ALL
             SELECT '2013-12-24'::date as start_date, '2014-01-23'::date as end_date
             ) as periods
        ON "balance_transactions"."created" BETWEEN "periods"."start_date" AND "periods"."end_date"
     WHERE "balance_transactions"."account_id" = 6 
       AND "balance_transactions"."type" = 'charge' 
       AND "charges"."refunded" = false 
       AND "charges"."invoice" IS NOT NULL
     GROUP BY "periods"."start_date", "periods"."end_date"
    

    This should return you all the periods you're interested in in one single resultset. Since the query is 'generated' on the fly in your front-end you can add as many rows to the periods part as you want.

    Edit: with some trial and error I managed to get it working [in sqlFiddle][1] and updated the syntax above accordingly.

提交回复
热议问题