I have the following query:
SELECT DISTINCT
branch.id,
branch.name,
SUM(CAST(COALESCE(NULLIF(REPLACE(dia_anterior.col_9, ',', '.'), ''), '0.0') AS double precision)) AS total_venta,
SUM(CAST(COALESCE(NULLIF(REPLACE(dia_anterior.col_4, ',', '.'), ''), '0.0') AS double precision)) AS total_personas,
SUM(CAST(COALESCE(NULLIF(REPLACE(ocupacion_dia_anterior.col_3, ',', '.'), ''), '0') AS double precision)) AS total_ocupacion
FROM branches AS branch
INNER JOIN queries AS q_dia_anterior
ON q_dia_anterior.query_structure_id = (SELECT id FROM query_structures WHERE query_structures.slug = 'dia-anterior')
INNER JOIN queries AS q_ocupacion_dia_anterior
ON q_ocupacion_dia_anterior.query_structure_id = (SELECT id FROM query_structures WHERE query_structures.slug = 'ocupacion-dia-anterior')
INNER JOIN queries AS q_ventas_x_articulo_dia_anterior
ON q_ventas_x_articulo_dia_anterior.query_structure_id = (SELECT id FROM query_structures WHERE query_structures.slug = 'ventas-x-articulo-dia-anterior')
INNER JOIN branch_data AS dia_anterior
ON dia_anterior.query_id = q_dia_anterior.id
AND dia_anterior.branch_id = branch.id
INNER JOIN branch_data AS ocupacion_dia_anterior
ON ocupacion_dia_anterior.query_id = q_ocupacion_dia_anterior.id
AND ocupacion_dia_anterior.branch_id = branch.id
INNER JOIN branch_data AS ventas_x_articulo_dia_anterior
ON ventas_x_articulo_dia_anterior.query_id = q_ventas_x_articulo_dia_anterior.id
AND ventas_x_articulo_dia_anterior.branch_id = branch.id
WHERE
branch.account_id = 1
GROUP BY
branch.id,
branch.name
ORDER BY
2
When I group the results to sum the columns, looks like the values from different rows are concatenating, resulting in huge values.
Am I missing something?
Why am I getting the values summed up multiple times?
SELECT DISTINCTif you're also doing aGROUP BY.GROUP BYin combination with the aggregate functionSUM()is already returning a unique set of rows. So specifyingDISTINCT, as you observed, doesn't alter the results, but it is an unnecessary distraction. It also causes the server to sort and unique your results unnecessarily. Sorry I couldn't help you with your main problem, though!