SQL group by returns duplicated POSTGRESQL

Asked

Viewed 262 times

0

My query SQL is returning multiple Rows with the same id follows:

SELECT distinct (c.nome), c.id, c.email,c.telefone1,c.telefone2,
  SUM(a.valor) AS "valorDaCompra",u.id AS  "idLoja",u.nome AS  "nomeLoja", 
  SUM(a.qtd_pecas) AS "qtdPecasCompradas", a.data_hora as "dataHora",
  c.data_hora as "dataCadastro" 
FROM cliente as c
INNER JOIN atendimento AS a 
  ON a.id_cliente = c.id INNER JOIN usuario AS u
  ON a.id_loja = u.id 
WHERE a.id_empresa= 843
  AND a.id_loja IN (2855) 
  AND a.venda = true 
GROUP BY a.data_hora, c.id,a.id_cliente,u.id,c.data_hora 
HAVING SUM(a.valor) >= 2 AND SUM(a.valor) <= 20000
ORDER BY c.id DESC

Resultado da query trazendo resultado duplicado

1 answer

1

I do not know the structure of its tables, which makes the analysis a little difficult but, revise the following points:

  1. Relationship a. id_loja = u.id.. A user is a store ? If the answer is no. Your relationship is wrong.

  2. There are aggregations in your query SUM(a. value) and SUM(a. qtd_pecas). The rule is that all other fields are informed in GROUP BY. Staying that way: GROUP BY c.name, c.id, c.email, c.phone1, c.phone2, u.id, u.nome, a.data_hora, c.data_hora. In that case, the destinct is not necessary.

  3. It is likely that the customer’s name will appear several times if he has purchased on different days and times (a. time date).

  • What happens is this, the 3 option of the a.data_hora issue, the customer when buying on different dates doubles.

  • And yes the user is a store. How can I make the customer not get duplicated?

  • 1

    Removes the column (a. time date) of your query. This way the customer stops appearing more than once and the value of your purchase is added disregarding the date of purchase.

  • Get it here, just put max(a.data_hora) it returns correctly

  • Good!.. just have to keep in mind that this date and time that will appear is the last purchase, but that the value and quantity are all together.

  • That’s the very intention, vlw Jow

Show 1 more comment

Browser other questions tagged

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