Home > Net >  SQL SUM COLUMN FROM A SAME TABLE AND Multi ids
SQL SUM COLUMN FROM A SAME TABLE AND Multi ids

Time:12-25

I have this table...

Is there any way to get the sum associated with id 1?

The final result should be... 4300.

Question Picture

CodePudding user response:

You can use a recursive CTE to get all the linked users:

with recursive u as
(select t.id, t.`Referral id`, t.Balance from yourtable t where id = 1
union
select t.id, t.`Referral id`, t.Balance from u inner join yourtable t
on u.id = t.`Referral id`)
(select sum(Balance) from u)

Fiddle

CodePudding user response:

select Sum(Balance) 
from YourTableName 
where id=Referelid 
and Referelid  <=4
  • Related