问题
I have a column with running sum, but I would like to inverse the order in a new or same column
My Query is
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
Mi table is
date | ant | num_room | cumulative_room
28-04-2020 6 1 1
28-04-2020 3 1 2
28-04-2020 4 1 3
28-04-2020 7 1 4
28-04-2020 4 1 5
....
How I can do another variable with reverse order from cumulative_room?
date | ant | num_room | cumulative_room |reverse_cumulative room
28-04-2020 6 1 1 5
28-04-2020 3 1 2 4
28-04-2020 4 1 3 3
28-04-2020 7 1 4 2
28-04-2020 4 1 5 1
....
回答1:
Your complete code is
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`;
The idea behind this is
CREATE TABLE xxx_xxxx_xxxx ( `date` VARCHAR(10), `ant` INTEGER, `num_room` INTEGER, `cumulative_room` INTEGER ); INSERT INTO xxx_xxxx_xxxx (`date`, `ant`, `num_room`, `cumulative_room`) VALUES ('28-04-2020', '6', '1', '1'), ('28-04-2020', '3', '1', '2'), ('28-04-2020', '4', '1', '3'), ('28-04-2020', '7', '1', '4'), ('28-04-2020', '4', '1', '5');✓ ✓
SELECT t1.* ,t2.max_room - `cumulative_room` 'reverse_cumulative room' FROm xxx_xxxx_xxxx t1 INNER JOIN (SELECT MAX(`cumulative_room`) +1 max_room, `date` FROM xxx_xxxx_xxxx GROUP BY `date`) t2 ON t1.`date` = t2.`date`;date | ant | num_room | cumulative_room | reverse_cumulative room :--------- | --: | -------: | --------------: | ----------------------: 28-04-2020 | 6 | 1 | 1 | 5 28-04-2020 | 3 | 1 | 2 | 4 28-04-2020 | 4 | 1 | 3 | 3 28-04-2020 | 7 | 1 | 4 | 2 28-04-2020 | 4 | 1 | 5 | 1
db<>fiddle here
来源:https://stackoverflow.com/questions/62071686/how-to-create-an-inverse-ordered-variable-in-my-sql