I have the tables products and history and I need to group by name:
products = (id_product, name)
history = (id_history, id_product, amount)
I tried this SQL query but it isn’t grouped by name:
SELECT products.name, sum(history.amount) FROM history INNER JOIN products ON history.id_product = products.id_product GROUP BY products.name, history.amount, history.id_history;
This is the result:
Advertisement
Answer
You should only be grouping by the attributes you need to be aggregated. In this case, you need only products.name
.
SELECT products.name, sum(history.amount) AS [Amount] FROM history INNER JOIN products ON history.id_product = products.id_product GROUP BY products.name;
If you need to include products without history (assuming sum should be 0 instead of null
in this case), then you can use an OUTER JOIN
instead of INNER JOIN
to include all products:
SELECT products.name, COALESCE(sum(history.amount), 0) AS [Amount] FROM history RIGHT OUTER JOIN products ON history.id_product = products.id_product GROUP BY products.name;