Skip to content
Advertisement

SQL: How to group by with two tables?

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:

This is the result:

SQL result

Advertisement

Answer

You should only be grouping by the attributes you need to be aggregated. In this case, you need only 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:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement