Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Como criar uma variável ordenada inversa no meu sql


Seu código completo é
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`;

A ideia por trás disso é

db<>fiddle aqui