MySQL: Sorting duplicate numbers ascendingly
P粉763748806
P粉763748806 2023-07-25 12:41:47
0
1
524
<p>I have a table that looks like this: </p> <table class="s-table"> <thead> <tr> <th>id</th> <th>values</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> </tr> <tr> <td>2</td> <td>1</td> </tr> <tr> <td>3</td> <td>1</td> </tr> <tr> <td>4</td> <td>2</td> </tr> <tr> <td>5</td> <td>2</td> </tr> <tr> <td>6</td> <td>2</td> </tr> </tbody> </table> <p>I want to sort them ascendingly this way in some kind of loop. </p> <table class="s-table"> <thead> <tr> <th>id</th> <th>values</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> </tr> <tr> <td>4</td> <td>2</td> </tr> <tr> <td>2</td> <td>1</td> </tr> <tr> <td>5</td> <td>2</td> </tr> <tr> <td>3</td> <td>1</td> </tr> <tr> <td>6</td> <td>2</td> </tr> </tbody> </table> <p>I believe this can be done easily with PHP, but I wanted to see if I could do it with SQL. </p>
P粉763748806
P粉763748806

reply all(1)
P粉501683874

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

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

You can take a look at this demo.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template