MYSQL: 递增排序重复数字

huangapple go评论62阅读模式
英文:

MYSQL: Incremental Sorting of Duplicate Numbers

问题

我有一个类似这样的表格:

id values
1 1
2 1
3 1
4 2
5 2
6 2

我想要按照某种方式将它们递增排序,可以使用循环,以以下方式排序:

id values
1 1
4 2
2 1
5 2
3 1
6 2

我认为可以使用PHP轻松实现这个目标,但我想看看是否可以使用SQL来实现。

英文:

I have a table that looks like this:

id values
1 1
2 1
3 1
4 2
5 2
6 2

I would like to have them sorted incrementally in some sort of loop that orders them in this fashion

id values
1 1
4 2
2 1
5 2
3 1
6 2

I believe this could be done easily with PHP however I would like to see if this can be done using SQL.

答案1

得分: 1

使用 ROW_NUMBER() 窗口函数在 ORDER BY 子句中:

SELECT *
FROM tablename
ORDER BY ROW_NUMBER() OVER (PARTITION BY `values` ORDER BY id), 
         `values`;

查看示例。<br/>

英文:

Use ROW_NUMBER() window function in the ORDER BY clause:

SELECT *
FROM tablename
ORDER BY ROW_NUMBER() OVER (PARTITION BY `values` ORDER BY id), 
         `values`;

See the demo.<br/>

huangapple
  • 本文由 发表于 2023年7月17日 17:03:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定