Skip to content
Advertisement

Group by sum from two different table with the same id

I have created a simple butchery web application which has two tables: sells and bought.

The bought table will include the kilos and price of each meat the user bought ,and the sells table will also include the kilos and the price of each meat sold.

Each and every meat has their own id so for example if the user bought a goat which has an id of 2 it will insert in the column of meat id and if they sell the goat it will insert the same id in the column of meat id for sells table

Now what i wanted to do is create a simple analytic where when the user chooses the month from the checkbox it will give them the total amount of kilos,price bought and total amount of kilos,price sold for that selected month, so that the user can see how much profit they made for each meat and how much kilos they lost.

The user can choose multiple months and compare the stats. For example, if the user clicks on the checkbox of April and May ,it should give them the total amount of kilos bought and sold for those two months

bought table

Bought table

sell table

sell table

My sql code

JavaScript

code to fetch result

JavaScript

This is the result i get when check on April

enter image description here

This is the result i get when check on April and May

enter image description here

based on the result of April it shows that kilos and price multiply twice and i don’t want that to happen and when i check on April and May the result keeps on multiplying

Result i want when i on check April should be

JavaScript

Result i want when i click on April and May

JavaScript

Advertisement

Answer

This is a bit more complicated that it might seem. Joining, then aggregating, would multipy the amounts if there are multiple rows per customer in both tables. You must also consider the possibility that a user may have matches in only one of the two tables.

I woulud recommend union all:

JavaScript

In a real life situation, you woulud have a reference table for the meats, that you could left join from:

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