1
I have a table pedidos
, produtos
and another produtos_em_pedidos
described as follows:
produtos: id | nome
pedidos: id | data
produtos_em_pedidos: produto_id | pedido_id | quantidade
I need to select the products that occur most in orders, being able to filter by date.
An example I already obtained was to find the best selling products globally, without considering the quantity column, through the query:
select produto_id, count(produto_id) from produtos_em_pedidos group by produto_id order by count(produto_id) desc
Now how would I filter that by the date that’s on the table pedidos
(ex: WHERE data > 2015-01-01
) and how to multiply Count by column quantidade
?
EDIT: I was able to filter by dates through the following query:
SELECT produto_id, count(produto_id) FROM produtos_em_pedidos
WHERE pedido_id in (select id from pedidos where data > '2015-01-01')
AND pedido_id in (select id from pedidos where data < '2018-01-01')
GROUP BY produto_id
order by count(produto_id) DESC;
It is an option, another good would be to use a Join between the two tables and use the data as desired:
Select count(pep.produto_id) from produtos_em_pedidos pep join pedidos on(pep.pedido_id = pedidos.id and pedidos.data < '2018-01-01' ) group by produto_id order by count(pep.produto_id)
, Sort of like this.– edson alves
And how I would consider the column
quantidade
in Count?– Luiz
The Inner Join only takes the records that "match" with the condition, so giving a Count() it will count the records that fit
– edson alves
The end result was the same. But this form you gave me seems much more computationally effective. Thank you!
– Luiz
Oops, I’m glad you helped. Dispose.
– edson alves