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

Sådan opretter du en omvendt ordnet variabel i min sql

Din komplette kode er

SELECT
t1.*
, t2.max_room - `cumulative_room` 'reverse_cumulative room'
FROm (SELECT date,
                ant, 
                num_room,
                (@csum:= @csum + num_room) as cumulative_room
                from xxx_xxxx_xxxx
                WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
                AND(select @csum := 0) = 0
                order by date) t1
INNER JOIN (SELECT MAX(`cumulative_room`) +1 max_room,  `date` FROM (SELECT date,
                                                                            ant, 
                                                                            num_room,
                                                                            (@csum:= @csum + num_room) as cumulative_room
                                                                            from xxx_xxxx_xxxx
                                                                            WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
                                                                            AND(select @csum := 0) = 0
                                                                            order by date) t3 GROUP BY  `date`) t2
ON t1.`date` = t2.`date`;

Tanken bag dette er

db<>fiddle her




  1. Mysql/Php - Aktuel dato og tid

  2. MySQL JOIN og COUNT i en enkelt forespørgsel

  3. postgres:find alle heltalskolonner med dens nuværende maks. værdi i

  4. Flet flere .sql-tabeldumpfiler til en enkelt fil