Skip to content
Advertisement

MYSQL – Sum from multiple columns in one table divided by one row in a JOINED other table

I have 2 tables for my online orders: product_items & order

The product_item contains selling_price, qty and cost_price the order table includes cost_shipping and currency

I want to get a total of all the selling_price (* qty) and cost_price (* qty) and the cost_shipping for all orders (grouped by currency)

The problem is that when I sum the cost_shipping it adds up one cost_shipping for each item in the order (because they are JOINED)

So if order 1 had 2 items and a cost_shipping of €10 then it would return €20.

If I don’t SUM the cost_shipping then I just get the last value

I need these values to workout the margin on the order.

Any suggestions as to how I can achieve this?

Thanks in advance

TempPeck

Advertisement

Answer

You would need to aggregate the costs and prices per order in a subquery first, then join it with the orders, and aggregate by currency:

Side notes:

  • table aliases make the query easier to write, read and maintain; I modified your code to use them

  • always qualify each column in your queries with the table it belongs to; this makes it much easier to follow the logic; I added qualifiers for every column (I had to make a few assumptions, namely for the date column)

  • you should generally avoid surrounding every table and column name with backticks; they are needed only when the identifiers contain special characters, which is not the case here

  • there are discrepencies on the table names in your original query; I used those you described in the question

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