Query for sum of total value

Asked

Viewed 47 times

2

Question: Create a Query that produces a report with the following items:

  • a) Name of client;
  • b) Total value of the claim;
  • c) Sort by date (decreasing) and higher value (decreasing);

My difficulty is in making the sum of the total value per request, since the id_pedido is repeated in more than one item (e.g.: Id_request = 1, product value =5; Id_product = 1, ordering value 3), with the need to add them up to reach the total value per id_pedido. Everything must happen within SELECT.

SELECT pe.id_pedido, C.NOME_CLIENTE, PE.DATA_PEDIDO, P.VALOR_PRODUTO * IP.QUANTIDADE AS TOTAL_PED
FROM CLIENTES C
INNER JOIN PEDIDOS PE
ON c.id_cliente = pe.id_cliente
INNER JOIN ITEM_PEDIDOS IP
ON pe.id_pedido = ip.id_pedido
INNER JOIN produtos P
ON ip.id_produto = p.id_produto
ORDER BY pe.data_pedido, pe.id_pedido DESC;

Resultado da query descrita acima

  • "My difficulty is in making the sum of the total value per request, since the id_request is repeated in more than one item" but in the enunciated does not ask for the id, can simply remove it from the SELECT, or will not be able to group, group only by name and date

  • if I understand correctly you want to group the fields where have the same id_pedido adding up their values in the case of id_pedido = 20 the TOTAL_PEDIDO shall be equal to 23,61. Correct?

  • That’s right, that’s the point!!

  • Have you studied the GROUP BY?

1 answer

3


You need to group by id_pedido and use the SUM function to sum the fields that make up the total order value


SELECT pe.id_pedido, C.NOME_CLIENTE, PE.DATA_PEDIDO, SUM(P.VALOR_PRODUTO * IP.QUANTIDADE) AS TOTAL_PED
FROM CLIENTES C
INNER JOIN PEDIDOS PE
ON c.id_cliente = pe.id_cliente
INNER JOIN ITEM_PEDIDOS IP
ON pe.id_pedido = ip.id_pedido
INNER JOIN produtos P
ON ip.id_produto = p.id_produto
GROUP BY pe.id_pedido
ORDER BY pe.data_pedido, pe.id_pedido DESC;

  • Thank you!! Perfect! I made a small change to my scenario and it worked, as per your guidance: SELECT pe.id_request, C.NOME_CLIENTE, PE.DATA_PEDIDO, SUM(P.VALOR_PRODUTO * IP.QUANTITY) AS TOTAL_PED FROM CLIENTS C INNER JOIN ORDERS PE ON c.id_client = .id_client INNER JOIN ITEM_PEDIDOS IP
ON pe.id_pedido = ip.id_pedido
INNER JOIN produtos P
ON ip.id_produto = p.id_produto
GROUP BY pe.id_pedido, C.NOME_CLIENTE, PE.DATA_PEDIDO;

  • For nothing! Consider accepting the answer as a solution to your question @Bia.mts!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.