Mysql如何对行进行排序以使其看起来像这样(例如1 2 1 2)

时间:2018-12-28 11:05:34

标签: mysql

假设我有一个列Word,值A和B。例如:

Row Word
1   A
2   A
3   A
4   B
5   B
6   B

我想在MySql中对它们进行排序:

Row Word
1   A
2   B
3   A
4   B
5   A
6   B

如果我使用ms sql

SELECT Word FROM Test
ORDER BY row_number() OVER (PARTITION BY Word ORDER BY Word), Word

我该如何在mysql中编写代码?

1 个答案:

答案 0 :(得分:0)

我在MySQL 8中找到了一个解决方案。我的表是这样的:

Screenshot of table, 10 rows, 2 columns "ID" and "Word"

我的SQL代码是

SELECT Word
    FROM test
    ORDER BY ROW_NUMBER() OVER (PARTITION BY Word ORDER BY Word), Word;

因此该表的排序如下:

Screenshot of table, sorted

我在下面找到了一个代码,但没有正确提供A B A B顺序。

SELECT 
    x.Word 
FROM
    (Select 
                t.Word,
                CASE
                    WHEN @word != t.Word THEN @rownum := 0
        WHEN @word = t.Word THEN @rownum := @rownum + 1
        ELSE @rownum
                END AS rutbe,
                @word := t.Word
            From 
                test t, (SELECT @rownum := 0, @word ORDER BY @word) r
    ) x
ORDER BY x.rutbe, x.Word