There are 3 conceptual errors in that query, first of all, the group by must contain all the fields of the query that are not "calculated" (Say, added functions and sub-queries). Second, you are already making a join with the%% table% when you type ventas
, so the query is unnecessary, to express it more clearly (at least in SQL Server) you should write it:
FROM
comprador c
INNER JOIN --O LEFT JOIN si quieres que aparezca los compradores sin ventas.
ventas v
ON v.id_com = c.id_com
Finally, and given that the sub-query is unnecessary given the previously seen, the fields that we would need to project are: from comprador, ventas
, c.nombre
(can be c.id_com
but even if they are equal I prefer that they belong to the same table that v.id_com
) and c.nombre
(the result of the added function SUM(v.cantidad) TotalCantidadVentas
as SUM
). Here, because it has an aggregate function, it is strictly necessary that the rest of the fields outside the aggregate function are in the definition of TotalCantidadVentas
, that is:
GROUP BY c.id_com, c.nombre
Our query would finally be like:
SELECT c.id_com, c.nombre, SUM(v.cantidad) TotalCantidadVentas
FROM
comprador c
INNER JOIN --O LEFT JOIN si quieres que aparezca los compradores sin ventas.
ventas v
ON v.id_com = c.id_com
--WHERE
GROUP BY c.id_com, c.nombre
--Having
In the Group By
you can use expreciones with the slogan that all the fields of the must exist in the Group By.
In the WHERE
you can use expressions with any "projected" field of the query. From the Sum we have or others such as AVG, MAS, MIN, COUNT and even sub-queries that only use the projected fields of the superior query in their internal conditions.