1
I am performing the following consultation to bring the products with their last sale date:
SELECT
P.ID AS 'Código',
p.Nome,
CONVERT(decimal(18,2),pe.Valor_Custo) as 'Custo',
CONVERT(decimal(18,2),pe.Porcentagem) as 'Mark-up',
CONVERT(decimal(18,2),pe.Valor_Venda) as 'Venda',
e.Quantidade as 'Estoque',
(SELECT DISTINCT TOP 1 DATA FROM Venda
left join Venda_Item_Produto vip on vip.ID_Produto = p.ID
WHERE VENDA.Data BETWEEN '2018/01/16' AND '2019/01/16' AND vip.ID_Produto = p.ID
ORDER BY Data DESC) AS 'Data Última Venda'
FROM Produto P
left join Produto_Empresa pe on pe.ID_Produto = p.ID
left join Estoque e on e.ID_Produto = p.ID
However, in the LAST SALE DATE field, it brings me the same date in all the records. What I’m doing wrong?
Beyond the
DISTINCTbe over and theLEFT JOINcan pass toINNER JOINand remove thevip.ID_Produto = p.IDof the clauseWHERE, nothing seems to be wrong. Unless they all actually have the same last sale date.– João Martins
If you want to return a valid last sale date, you have to exchange the
left join Venda_Item_Produtoforinner join Venda_Item_Produto.– Marcelo Shiniti Uchimura