sql >> Base de Datos >  >> RDS >> Mysql

Cómo crear una variable ordenada inversa en mi sql

Su código completo es

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`;

La idea detrás de esto es

db<>fiddle aquí