select a.no, a.Dtime,count(b.Dtime)+1 as Rank
from table1 a left
join table1 b on a.Dtime>b.Dtime and a.no=b.no
group by a.no,a.Dtime
order by a.no, a.Dtime


table1输入:

NO  Dtime
1   08:10:00
1   09:10:00
1   09:40:00
1   10:10:00
2   09:30:00
2   10:15:00
3   09:00:00


输出:

NO  Dtime       Rank
1   08:10:00    1
1   09:10:00    2
1   09:40:00    3
1   10:10:00    4
2   09:30:00    1
2   10:15:00    2
3   09:00:00    1


但是我正在寻找在mysql中的输出,其中table2排名链接到table1和table2 Dtime,即table1.Dtime> table2.time

table2输入

NO  Dtime
1   08:30:00
1   09:15:00
1   09:50:00
2   08:30:00
2   09:45:00
3   09:50:00


输出:

NO  table1.Dtime    Rank    table2.Dtime
1   08:10:00        0       00:00:00
1   09:10:00        1       08:30:00
1   09:40:00        2       09:15:00
1   10:10:00        3       09:50:00
2   09:30:00        1       08:30:00
2   10:15:00        2       09:45:00
3   09:00:00        0       00:00:00

最佳答案

您可以对初始查询使用相同的方法。只需left jointable2。要从Dtime获取table2,可以使用相关子查询:

select a.no, a.Dtime,
       count(b.Dtime) as Rank,
       coalesce((select c.Dtime
       from table2 as c
       where c.no = a.no and a.Dtime > c.Dtime
       order by c.Dtime desc limit 1), '00:00:00') as t2Dtime
from table1 a
left join table2 b on a.Dtime > b.Dtime and a.no = b.no
group by a.no,a.Dtime
order by a.no, a.Dtime


Demo here

关于mysql - 基于多个表的排名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49270483/

10-13 08:57