0
My doubt is a little boring to explain but I’ll try to make it as simple as possible.
I have the following tables in a Mysql database: produto
, preco
, preco_produto
(many mapping to many), venda
and itens_venda
.
I need a consultation for a report that returns the amount of outputs (in sales) of these products, and the stipulated income that these outputs generated. I also want to maintain the relationship of preco_produto
, because it is to be clear that the outputs of that product were made at the time that a certain price was worth.
So I came in for a consultation sort of like this:
SELECT p.nome AS produto, SUM(iv.quantidade) AS qtd, pp.preco_venda AS preco,
(SUM(iv.quantidade)*pp.preco_venda) AS renda
FROM tb_venda v
INNER JOIN tb_item_venda iv
ON (v.id = iv.tb_venda_id)
INNER JOIN tb_preco_produto pp
ON (iv.tb_preco_produto_id = pp.id)
INNER JOIN tb_produto p
ON (pp.tb_produto_id = p.id)
WHERE v.tb_status_venda_id = 3
GROUP BY pp.id
ORDER qtd DESC, BY p.nome ASC
Only this returns the records to me as follows:
+---------+-------+-------+-------+
| produto | qtd | preco | renda |
+---------+-------+-------+-------+
| Esfirra | 40 | 2.2 | 88 |
| Coxinha | 35 | 2 | 70 |
| Beirute | 30 | 2.5 | 75 |
| Esfirra | 20 | 2 | 40 |
When in fact I wanted them returned like this, ordered by quantity and by name:
+---------+-------+-------+-------+
| produto | qtd | preco | renda |
+---------+-------+-------+-------+
| Esfirra | 40 | 2.2 | 88 |
| Esfirra | 20 | 2 | 40 |
| Coxinha | 35 | 2 | 70 |
| Beirute | 30 | 2.5 | 75 |
Is there any way to get this result working only in SQL query?
PS.: If you need any more details let me know.
Let me see if I understand "Esfirra" has the biggest "Qtd", so first order by itself that there is a "20" for "Esfira" and a "35" for "Coxinha"? This being create a column max(iv.quantity) AS maxqtd grouping by product and sort by this 'max"
– Motta
That’s right @Motta. But if I group by product I lose the "preco_product" ratio and then instead of appearing two esfirras in the result, only one will appear. As for the MAX(iv.quantity), it will not work because if I sort by the largest amount of selling items, it will not solve. Maybe if I did something like MAX(SUM(iv.quantidade)), but Mysql wouldn’t let me do it.
– Simão Ítalo
How it comes out by changing the order: ORDER BY p.ASC name, Qtd DESC?
– Reginaldo Rigo
@Reginaldorigo, the result comes out in ascending order by product name. For example, first would come the "Beirut" with 30, then the "Coxinha" with 35 and then the "Esfirra" with 40, with the "Esfirra" with 20 soon after.
– Simão Ítalo
You can put a query out of this by taking the nicknames and using them in ORDER BY.
– Lindomar Lemos
If you order first by product and then by quantity does not work?
– Fleuquer Lima