How to show rows in packs of three in MySQL

白昼怎懂夜的黑 提交于 2019-12-11 05:34:51

问题


I have a table like this:

ID  Type  Timestamp
1   A     101   
2   A     102
3   B     103
4   B     104   
5   A     105   
6   B     106   
7   A     107
8   A     108
9   B     109   
10  A     110   
11  B     111
12  B     112
...

I want to show a result sorted by Type and Timestamp where every 3 rows the Type changes like this:

ID  Type  Timestamp
1   A     101
2   A     102
5   A     105
3   B     103
4   B     104
6   B     106
7   A     107
8   A     108
10  A     110
9   B     109
11  B     111
12  B     112
...

回答1:


If you are running MySQL 8.0, consider:

SELECT *
FROM mytable
ORDER BY 
    FLOOR((ROW_NUMBER() OVER(PARTITION BY type ORDER BY timestamp) - 1)/3),
    type, 
    timestamp

Demo on DB Fiddle:

| id  | type | timestamp |
| --- | ---- | --------- |
| 1   | A    | 101       |
| 2   | A    | 102       |
| 5   | A    | 105       |
| 3   | B    | 103       |
| 4   | B    | 104       |
| 6   | B    | 106       |
| 7   | A    | 107       |
| 8   | A    | 108       |
| 10  | A    | 110       |
| 9   | B    | 109       |
| 11  | B    | 111       |
| 12  | B    | 112       |

In earlier versions, you can use variables to emulate ROW_NUMBER():

SELECT id, type, timestamp
FROM (
    SELECT 
        t.*, 
        @rn := CASE WHEN @type = type THEN @rn + 1 ELSE 1 END rn,
        @type := type
    FROM 
        mytable t
        CROSS JOIN (SELECT @type := NULL, @rn := 1) x
    ORDER BY type, timestamp
) x
ORDER BY 
    FLOOR((rn - 1)/3),
    type, 
    timestamp;

Demo on DB Fiddle



来源:https://stackoverflow.com/questions/58167289/how-to-show-rows-in-packs-of-three-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!