Tengo que obtener una lista con los clientes de la empresa a los que hemos facturado algo durante el presente año, indicando cuánto hemos facturado cada mes.
Tengo dos tablas: la tabla de clientes (customer) y la tabla de facturas (invoice). La relación es la evidente: un cliente puede tener muchas facturas, y cada factura está relacionada con un único cliente.
Lo único que se me ha ocurrido es lo siguiente:
select id,
name as "Nombre",
identity_number as "CIF",
(select sum(total)
from invoice
where payment_date between '2017-01-01' and '2017-02-01' and customer_id=c.id group by customer_id) as "Enero",
(select sum(total)
from invoice
where payment_date between '2017-02-01' and '2017-03-01' and customer_id=c.id group by customer_id) as "Febrero",
(select sum(total)
from invoice
where payment_date between '2017-03-01' and '2017-04-01' and customer_id=c.id group by customer_id) as "Marzo",
(select sum(total)
from invoice
where payment_date between '2017-04-01' and '2017-05-01' and customer_id=c.id group by customer_id) as "Abril",
(select sum(total)
from invoice
where payment_date between '2017-05-01' and '2017-06-01' and customer_id=c.id group by customer_id) as "Mayo",
(select sum(total)
from invoice
where payment_date between '2017-06-01' and '2017-07-01' and customer_id=c.id group by customer_id) as "Junio",
(select sum(total)
from invoice
where payment_date between '2017-07-01' and '2017-08-01' and customer_id=c.id group by customer_id) as "Julio",
(select sum(total)
from invoice
where payment_date between '2017-08-01' and '2017-09-01' and customer_id=c.id group by customer_id) as "Agosto",
(select sum(total)
from invoice
where payment_date between '2017-09-01' and '2017-10-01' and customer_id=c.id group by customer_id) as "Septiembre",
(select sum(total)
from invoice
where payment_date between '2017-10-01' and '2017-11-01' and customer_id=c.id group by customer_id) as "Octubre",
(select sum(total)
from invoice
where payment_date between '2017-11-01' and '2017-12-01' and customer_id=c.id group by customer_id) as "Noviembre",
(select sum(total)
from invoice
where payment_date between '2017-12-01' and '2017-12-31' and customer_id=c.id group by customer_id) as "Diciembre"
from customer c
where c.branding_id=1 and (select sum(total)
from invoice
where payment_date between '2017-01-01' and '2017-12-31' and customer_id=c.id group by customer_id) > 0
Esto funciona, pero lo encuentro extremadamente ineficiente (hay 13 subconsultas, si incluimos la del WHERE). ¿Hay algún modo de simplificar esta consulta o es la mejor forma de obtener los datos?