Sum for multiple date ranges in a single call?

前端 未结 10 1788
有刺的猬
有刺的猬 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:36

    SELECT periods.start_date, 
         periods.end_date, 
         SUM(fee) AS Period_Sum
    FROM "balance_transactions" 
    JOIN charges ON balance_transactions.source = charges.balance_id 
    JOIN
    (SELECT CAST('2013-12-20' AS DATE) AS start_date, CAST('2014-01-19' AS DATE) AS end_date UNION     ALL
     SELECT  CAST('2013-12-21' AS DATE),CAST('2014-01-20'  AS DATE) UNION ALL
     SELECT  CAST('2013-12-22' AS DATE),  CAST('2014-01-21' AS DATE) UNION ALL
     SELECT CAST('2013-12-23' AS DATE),  CAST('2014-01-22' AS DATE) UNION ALL
     SELECT  CAST('2013-12-24' AS DATE), CAST('2014-01-23' AS 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
    

    Here is link to SQL Fiddle Where I tested it: http://sqlfiddle.com/#!10/535ac/11/0

提交回复
热议问题