最佳答案
怎么做?
以前这个问题的标题是“ 在子查询的复杂查询中使用 rank (@Rank: =@Rank + 1)-这样能行吗?”,因为我一直在寻找解决方案使用等级,但现在我看到的解决方案是由比尔张贴更好。
原问题:
我正在尝试编写一个查询,根据给定的顺序从每个组获取最后的记录:
SET @Rank=0;
select s.*
from (select GroupId, max(Rank) AS MaxRank
from (select GroupId, @Rank := @Rank + 1 AS Rank
from Table
order by OrderField
) as t
group by GroupId) as t
join (
select *, @Rank := @Rank + 1 AS Rank
from Table
order by OrderField
) as s
on t.GroupId = s.GroupId and t.MaxRank = s.Rank
order by OrderField
表达式 @Rank := @Rank + 1
通常用于排名,但对我来说,当在2个子查询中使用时,它看起来可疑,但是只初始化了一次。这样行得通吗?
其次,它是否能够处理一个被多次计算的子查询?比如 where (或 have)子句中的子查询(另一种写法) :
SET @Rank=0;
select Table.*, @Rank := @Rank + 1 AS Rank
from Table
having Rank = (select max(Rank) AS MaxRank
from (select GroupId, @Rank := @Rank + 1 AS Rank
from Table as t0
order by OrderField
) as t
where t.GroupId = table.GroupId
)
order by OrderField
先谢谢你!