我的数据集中有多组城市,我正在尝试为mysql中的每个组排序。有人可以帮我转换分区子句到mysql吗?
答案 0 :(得分:1)
我假设你正在寻找相当于rank() over (partition by city order by price)
的东西。您可以使用子查询执行此操作:
select d.*,
(select 1 + count(price)
from dataset d2
where d2.city = d.city and d2.price < d.price
) as rank
from dataset d;
或使用变量:
select d.*,
(@rn := if(@city = city and @price > price, if(@price = @price, @rn + 1, @rn + 1),
if(@city = city and @price = price, @rn,
if(@city := city, if(@price := price, 1, 1), 1)
)
)
) as rank
from dataset d cross join
(select @rn := 0, @city := '', @price = -1)
order by city, price;