Sum lines after comparing one line to multiple lines
I have two tables to be a
and b
. I want to compare number
in a
with number
in b
where they have an id. a
has one line and b
several. If the amount is b
less than a
, then this line from a
should be added to the total amount, 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 this example: b 1 and 2 are greater than 4, so it will not count. b 3 and 4 are less than 5, so it will count. b 5 and 6 are less than 6, so it will count. The amount should be 130.
I am having trouble doing a one-to-several string comparison and then summing some numbers.
source to share
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
Conceptually, the simplest option is to create a temporary table containing the sums of table b and then to JOIN
, which are returned to table a. The proposal WHERE
limits your total to only values Number
greater than the sum of b.
source to share