Mysql
 sql >> Base de données >  >> RDS >> Mysql

Comment créer une variable ordonnée inverse dans mon sql

Votre code complet est

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

L'idée derrière cela est

db<>violon ici