sql >> Base de Datos >  >> RDS >> PostgreSQL

¿Suma para múltiples rangos de fechas en una sola consulta?

Suponiendo que entiendo su solicitud correctamente, creo que lo que necesita es algo como esto:

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"

Esto debería devolverle todos los períodos que le interesan en un solo conjunto de resultados. Dado que la consulta se 'genera' sobre la marcha en su interfaz, puede agregar tantas filas a la parte de períodos como desee.

Editar:con algunas pruebas y errores logré que funcionara [en sqlFiddle][1] y actualicé la sintaxis anterior en consecuencia.