Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum rows after comparing one row with multiple rows

Tags:

mysql

I have two tables that will be a and b. I want to compare number in a to number in b where they share an ID. a has a single row, while b has multiple. If the sum of b is less than a, then that row of a should be added to the total sum, otherwise it should be skipped.

Table a
ID  Number
4   50
5   60
6   70

Table b
ID  Number  SharedID
1   30      4
2   25      4
3   50      5
4   5       5
5   30      6
6   10      6

Using that example: b 1 and 2 are greater than a 4, so it wouldn't be counted. b 3 and 4 are less than a 5 so it would count. b 5 and 6 are less than a 6, so it would count. The total should be 130.

I'm having trouble with doing a comparison of one row to multiple and then only summing some of the numbers.

like image 777
Rhyono Avatar asked Jul 03 '26 06:07

Rhyono


2 Answers

This should do the job:

select sum(Number)
from a
where Number > (select sum(Number) from b where b.SharedID = a.ID)
like image 79
Giorgi Nakeuri Avatar answered Jul 05 '26 21:07

Giorgi Nakeuri


Try this query:

SELECT SUM(a.Number)
FROM a INNER JOIN
(
    SELECT b.SharedID, SUM(b.Number) AS theSum
    FROM b
    GROUP BY b.SharedID
) t
ON a.ID = t.SharedID
WHERE t.theSum < a.Number

The conceptually easiest option is to create a temporary table containing the sums of Table b, and then to JOIN that back to Table a. The WHERE clause restricts your total to only a Number values which are greater than the b sum.

like image 35
Tim Biegeleisen Avatar answered Jul 05 '26 20:07

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!