简体   繁体   中英

SQL - Get Month Name and SUM() of every month

I have the following task to perform on a table:

  • Show the months name , the quantity of orders and the total value of order for each month

and I have a diagram for my current tables Tables

I'm sorry that it's in a foreign language but I'll translate.

  • Pedido stands for Order
  • Produto for Product Cliente for Client and
  • Item_Pedido for Order_Item

I've tried joining the tables and then trying to grab the month by name but failed miserably, any help is appreciated!

I'm assuming I'll have to GROUP BY the SELECT result from the orders date?

This is Oracle SQL

Tried query

SELECT Clientte.nm_cliente, Item_pedido.nr_quantidade "Quantidade", Pedido.dt_venda 
FROM Clientte INNER JOIN Pedido
ON Clientte.id_cliente = Pedido.id_cliente
INNER JOIN Item_pedido
ON Pedido.id_pedido = item_pedido.id_pedido
INNER JOIN Produto
ON item_pedido.id_produto= Produto.id_Produto;

I think you might want something like this.

SELECT to_char(Pedido.dt_venda, 'Month') as mon, 
    Clientte.nm_cliente, 
    count(distinct id_pedido) as num_orders,
    sum(Item_pedido.nr_quantidade * produto.nr_preco) total_value 
FROM Clientte 
INNER JOIN Pedido
  ON Clientte.id_cliente = Pedido.id_cliente
INNER JOIN Item_pedido
  ON Pedido.id_pedido = item_pedido.id_pedido
INNER JOIN Produto
  ON item_pedido.id_produto= Produto.id_Produto
GROUP BY to_char(Pedido.dt_venda, 'Month');

Two assumptions - you say you want "the quantity of orders", so I'm assuming you mean the number of unique ID_PEDIDOs for that month. You might instead want sum(nr_quantidade) , the total number of items ordered, I'm not sure.

Second, you want "the total value of order", which I'm assuming means the total item quantity * price for all items in each order.

SELECT Count(*), ID_PEDIDO, EXTRACT(month FROM date) FROM Pedido 
GROUP BY ID_PEDIDO, EXTRACT(month FROM date)

Can you see if this gets you closer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM