search

Home  >  Q&A  >  body text

MySQL: Sorting duplicate numbers ascendingly

<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粉763748806P粉763748806497 days ago529

reply all(1)I'll reply

  • P粉501683874

    P粉5016838742023-07-26 10:47:39

    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.

    reply
    0
  • Cancelreply