Group duplicate Sql Server lines

Asked

Viewed 1,462 times

1

I created the query where I have a table Products and another stock (1:N) need to add the stock of each product has in the stock table, I made the following query:

select DISTINCT p.ID,IsNull(p.CodigoBarra, '') As 
CodBarra,IsNull(p.CodigoAlternativo, '') As 
CodAlt,p.Descricao,p.DescricaoAlternativa,f.Descricao as Fabricante, 
sum(est.EstoqueAtual) as EstoqueAtual, COUNT(est.EstoqueAtual) as 
QtdEsnderecosEstoque from produto p
inner join Fabricante f on f.ID = p.FabricanteID
left join EstoqueLoteLocalizacao est on est.ProdutoId = p.ID
where p.DataExclusao is null and p.EmpresaID = 3
group by p.ID,p.CodigoBarra,p.CodigoAlternativo,p.Descricao,p.DescricaoAlternativa,f.Descricao, est.EstoqueAtual

This Query returns me the following:

inserir a descrição da imagem aqui

What I need is that instead of him giving me the 2 records, he group and the current stock there is added 4000 - -40 and me display in 1 record only the value of 3960

1 answer

1


When you use grouper function (such as SUM), it will take into account all lines that are differentiated by GROUP BY.

In case, your GROUP BY included in its column clause est.EstoqueAtual. If you remove this column from GROUP BY, he will group it and it will be added as desired.

  • 1

    It worked, I had put it in Group By because I was giving this error: The 'Manufacturer.Description' column is invalid in the selection list because it is not contained in an aggregation function or in the GROUP BY clause. however the error by q vi did not fit her and I put in the same impulse, but in order, Thank you very much for the explanation

  • @Edenilsonbile these things are very difficult to perceive, usually only an external reviewer to see

Browser other questions tagged

You are not signed in. Login or sign up in order to post.