我有一个查询
select time, a, b, c from table order by time asc
time a b c
1 x x x
2 y y y
3 z z z
我想以相反的顺序向查询中添加列时间。原始查询应保持相同的结构和顺序。
select time, time_reverse, a, b, c from table order by time asc
time a b c time_reverse
1 x x x 3
2 y y y 2
3 z z z 1
对不起,我尝试了几种方法并使用了google,但找不到此解决方法,也许很简单。
答案 0 :(得分:1)
使用窗口函数将row_number添加到结果集中,然后将其自身重新连接起来,可能在这里起作用:
WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY `time`) as rn,
ROW_NUMBER() OVER ORDER BY `time` DESC) as rn2
FROM yourtable
)
SELECT cte.time, cte.a, cte.b, cte.c, cte2.time
FROM cte INNER JOIN cte2 ON cte.rn = cte.rn2
ORDER BY cte.time;
rn
和rn2
只是行号,其中一个是另一个的反向编号。加入该链接可以为您提供所需的输出。
答案 1 :(得分:0)
可以使用窗口函数(自MySQL 8.0起)解决该问题。 您需要按row_number()值连接两个具有不同顺序的查询:
select
table.*,
reverted.time as reverted_time
from
(
select
time, a, b, c, row_number() over (order by time asc) rownum
from table
) table
join (
select
time, row_number() over (order by time desc) rownum
from table
) reverted on reverted.rownum = table.rownum;