sql >> Database teknologi >  >> RDS >> Mysql

MySQL SUM med samme ID

Prøv denne løbende total:http://www.sqlfiddle.com/#!2/ ce765/1

select  
    bid as no, value,
    @rt := if(aid = @last_id, @rt + value, value) as total,
    @last_id := aid
from table_b b, (select @rt := 0 as x, @last_id := null) as vars
order by b.bid, b.aid;
 

Output:

| NO | VALUE | TOTAL | @LAST_ID := AID | |----|-------|-------|-----------------| | 1 | 10 | 10 | 1 | | 2 | 15 | 25 | 1 | | 3 | 5 | 5 | 2 | | 4 | 10 | 15 | 2 | | 5 | 25 | 25 | 3 | | 6 | 40 | 65 | 3 |

Slut dig derefter til tabel A, sidste forespørgsel:

select x.no, x.aid, x.value, x.total, a.value - x.total as balance
from
(
  select    
    bid as no, aid, value,
    @rt := if(aid = @last_id, @rt + value, value) as total,
    @last_id := aid
  from table_b b, (select @rt := 0 as x, @last_id := null) as vars
  order by b.bid, b.aid
) as x
join table_a a using(aid)
 

Output:

| NO | AID | VALUE | TOTAL | BALANCE | |----|-----|-------|-------|---------| | 1 | 1 | 10 | 10 | 90 | | 2 | 1 | 15 | 25 | 75 | | 3 | 2 | 5 | 5 | 45 | | 4 | 2 | 10 | 15 | 35 | | 5 | 3 | 25 | 25 | 125 | | 6 | 3 | 40 | 65 | 85 |

Live test:http://www.sqlfiddle.com/#!2/ce765/ 1

OPDATERING

Ikke afhængig af kolonne bud sortering, kørende total på gruppering vil ikke blive påvirket:http://www.sqlfiddle. com/#!2/6a1e6/3

select x.no, x.aid, x.value, x.total, a.value - x.total as balance
from
(
  select    
    @rn := @rn + 1 as no, aid, value,
    @rt := if(aid = @last_id, @rt + value, value) as total,
    @last_id := aid
  from table_b b, (select @rt := 0 as x, @last_id := null, @rn := 0) as vars
  order by b.aid, b.bid
) as x
join table_a a using(aid)
 

Output:

| NO | AID | VALUE | TOTAL | BALANCE | |----|-----|-------|-------|---------| | 1 | 1 | 10 | 10 | 90 | | 2 | 1 | 15 | 25 | 75 | | 3 | 1 | 7 | 32 | 68 | | 4 | 2 | 5 | 5 | 45 | | 5 | 2 | 10 | 15 | 35 | | 6 | 3 | 25 | 25 | 125 | | 7 | 3 | 40 | 65 | 85 |

Live test:http://www.sqlfiddle.com/#!2/6a1e6/ 3



  1. Kan ikke oprette forbindelse til postgres fra fjernvært

  2. Minimumsadgangsniveauer for at køre MySql-lagret procedure

  3. Opret trigger for at logge SQL, der påvirkede tabel?

  4. Laravel:hvordan tilføjes hvor-klausul ved hjælp af forespørgselsbyggeren?