1

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?

2 respuestas 2

3

EDIT: después de redactar esta respuesta (para MySQL) me di cuenta de que la pregunta era en PostgreSQL. La sintaxis correcta está en la respuesta del OP.

Primero, la cláusula final (que la suma de pagos de enero a diciembre de 2017 sea mayor a cero) es lo mismo que decir que payment_date sea del año 2017.

Segundo, suponiendo que tu tabla invoice es y contiene:

create table invoice (customer_id integer, total integer, payment_date datetime);
insert into invoice values (1, 5, now());
insert into invoice values (1, 15, NOW() - INTERVAL 1 DAY);
insert into invoice values (1, 45, NOW() - INTERVAL 41 DAY);
insert into invoice values (1, 12, NOW() - INTERVAL 61 DAY);
insert into invoice values (1, 13, NOW() - INTERVAL 91 DAY);
insert into invoice values (2, 55, now());
insert into invoice values (2, 15, NOW() - INTERVAL 21 DAY);
insert into invoice values (3, 145, NOW() - INTERVAL 71 DAY);
insert into invoice values (3, 1, NOW() - INTERVAL 16 DAY);
insert into invoice values (3, 3, NOW() - INTERVAL 121 DAY);

puedes ir haciendo en cada columna:

SUM(IF(MONTH(payment_date)=1, total, 0) as enero

Esto quedaría algo como:

select customer_id,
  SUM(IF(month(payment_date)=12,total,0)) as diciembre,
  SUM(IF(month(payment_date)=11,total,0)) as noviembre,
  SUM(IF(month(payment_date)=10,total,0)) as octubre,
  SUM(IF(month(payment_date)=9,total,0)) as septiembre,
  SUM(IF(month(payment_date)=8,total,0)) as agosto
from invoice
where year(payment_date)=2017
group by customer_id

introducir la descripción de la imagen aquí

No incluí todos los meses ni el JOIN con la tabla de clientes, esa parte te la dejo de tarea, pero si quieres listar todos los clientes, incluyendo los que no pagaron nada este año, el FROM tendría que ser

FROM customer c LEFT JOIN invoice on customer_id=c.id AND YEAR(payment_date)=2017

Fiddle de ejemplo

2
  • Tu respuesta me ha sido útil para encontrar muchas mejoras, pero no sé para qué DBMS está escrita porque he tenido que buscar el equivalente a muchos detalles: no hay IF(..) o month(...) o year(...)en postgresql 9.4 el 12 dic. 2017 a las 11:58
  • Esta conversación ha sido trasladada a un chat por petición del autor de la pregunta.
    – lois6b
    el 12 dic. 2017 a las 12:03
1

Basado en la respuesta de @amenadiel (que es correcta para MySQL), he creado la siguiente consulta:

select c.id, 
c.name as "Nombre",
c.identity_number as "CIF", 
  SUM(CASE WHEN date_part('month',i.payment_date)=12 then total else 0 end ) as diciembre,
  SUM(CASE WHEN date_part('month',i.payment_date)=11 then total else 0 end) as noviembre,
  ...
  SUM(CASE WHEN date_part('year',i.payment_date)=2017 then total else 0 end) as TOTAL
from customer c join invoice i on c.id=i.customer_id
where date_part('year',i.payment_date)=2017 and c.branding_id=2
group by c.id
order by c.id

Como curiosidad, la consulta de la pregunta necesitaba casi dos minutos en ejecutarse mientras que esta solución tarda alrededor de 300ms en mostrar los mismos resultados

1
  • 1
    La mejora en rendimiento es normal, y es porque en vez de recorrer la tabla invoice 12 veces por registro, solo lo recorres una vez en el join. Una gran diferencia. Si quieres mejorar el rendimiento aun más, modificaría la condición where date_part('year',i.payment_date)=2017 a where i.payment_date >= '2017-01-01' and i.payment_date < '2018-01-01'. Esto permitiría el uso de índice en la columna payment_date si la tienes definida. Usando date_part('year', i.payment_date), no es posible usar un indíce en esa columna.
    – sstan
    el 12 dic. 2017 a las 14:01

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.