Make a subquery that returns all desired stock Ids using max()
, grouping by what they have in common, which from what I understood from your question is the id_produto
. You can even already filter the store to generate a smaller recordset and streamline the query ahead. As for example:
select * from estoque
where id in (select max(id) from estoque where loja = 16 group by id_produto);
Or, avoiding the use of in
and making join
for best performance:
select * from estoque e1 join
(select max(id) as id from estoque where loja = 16 group by id_produto) e2
on e1.id = e2.id
This would result in a stock id (the largest, or most recent) for every product in that store:
| id | id_produto | loja |
|----|------------|------|
| 4 | 2 | 16 |
| 5 | 3 | 16 |
| 8 | 1 | 16 |
| 9 | 4 | 16 |
Finally, just stick this filtered stock in your query that makes join
with the product table to pick up descriptions, etc. I suggest using CTE with with
, that makes the whole thing much more readable:
with e as (
select e1.id, e1.id_produto, e1.loja from estoque e1 join
(select max(id) as id from estoque
where loja = 16 group by id_produto) e2
on e1.id = e2.id
)
select
e.id,
p.gtin,
p.descricao,
e.loja
from produto p join e on p.id = e.id_produto;
It would return to you something like:
| id | gtin | descricao | loja |
|----|------|-----------|------|
| 8 | 0001 | Produto a | 16 |
| 4 | 0002 | Produto b | 16 |
| 5 | 0003 | Produto c | 16 |
| 9 | 0004 | Produto d | 16 |
The following is an example in SQL Fiddle: http://sqlfiddle.com/#! 17/c67dd/4
In this fiddle you can see that I set up a simplified schema, but based on what you presented by your question. If there’s anything that doesn’t fit in your schema, I suggest you post a fiddle with a sample of the data so we can perform more reliable tests.
Resolved... Thank you very much to everyone who helped me!
– Lenicio de Souza Melo Junior