Sum for multiple date ranges in a single call?

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

    It hasn't been mentioned yet and would not be as efficient as a single select BUT as a solution you could use a UNION and group by your own static identifier (date range group) such as:

    SELECT 
       'a' AS DateRangeIdentifier,
       SUM("balance_transactions"."fee") AS sum_id 
       FROM "balance_transactions" 
       JOIN charges ON balance_transactions.source = charges.balance_id 
       WHERE "balance_transactions"."account_id" = 6 
          AND (balance_transactions.type = 'charge' 
          AND charges.refunded = false 
          AND charges.invoice IS NOT NULL) 
          AND ("balance_transactions"."created" BETWEEN '2013-01-01' AND '2013-01-31')
    
    UNION 
    
    SELECT 
       'b' AS DateRangeIdentifier,
       SUM("balance_transactions"."fee") AS sum_id 
       FROM "balance_transactions" 
       JOIN charges ON balance_transactions.source = charges.balance_id 
       WHERE "balance_transactions"."account_id" = 6 
          AND (balance_transactions.type = 'charge' 
          AND charges.refunded = false 
          AND charges.invoice IS NOT NULL) 
          AND ("balance_transactions"."created" BETWEEN '2013-07-01' AND '2013-07-31')
    
    UNION 
    
    SELECT 
       'c' AS DateRangeIdentifier,
       SUM("balance_transactions"."fee") AS sum_id 
       FROM "balance_transactions" 
       JOIN charges ON balance_transactions.source = charges.balance_id 
       WHERE "balance_transactions"."account_id" = 6 
          AND (balance_transactions.type = 'charge' 
          AND charges.refunded = false 
          AND charges.invoice IS NOT NULL) 
          AND ("balance_transactions"."created" BETWEEN '2013-12-20' AND '2014-01-19')
    
    GROUP BY DateRangeIdentifier, sum_id
    

    This way would at least yield a single database request and not a loop in your code.

    See updated Fiddle here: http://sqlfiddle.com/#!15/9ce0f/5

提交回复
热议问题