mysql 中的复杂旋转

Complex pivoting in mysql

我在 MySQL 中有一个 table 有数据,我想从 table 实现某种旋转,这对我来说变得很复杂。我已经尝试调查 this 但似乎对我没有任何帮助。这是我的 table 的结构:

roomid| day| 1 | 2 | 3 | 4 | 5 | 6 |
------+----+---+---+---+---+---+---+
1     | 1  |BIO|   |   |   |   |   |
1     | 2  |   |CHE|   |   |   |   |
1     | 3  |   |   |   |   |   |ENG|     
1     | 4  |   |   |KIS|   |   |   |
1     | 5  |   |   |   |   |   |PHY|  
2     | 1  |BIO|   |   |   |   |   | 
2     | 2  |   |CHE|   |   |   |   |
2     | 3  |   |   |   |   |ENG|   |     
2     | 4  |   |   |KIS|   |   |   | 
2     | 5  |   |   |   |   |   |PHY|     

这个table是holding timetable的数据,roomid是房间的id,day是周一到周五(1到5)的天数。 1 到 6 列是周期 ID。 我需要组织数据以获得每天显示每个 class 期间 ID 的结果。像这样:

|roomid| 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 | 5 | 6 |
-------+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
1      |BIO|   |   |   |   |   |   |CHE|   |   |   |   |   |   |   |   |   |ENG|   |   |KIS|   |   |   |   |   |   |   |   |PHY|
2      |BIO|   |   |   |   |   |   |CHE|   |   |   |   |   |   |   |   |   |ENG|   |   |KIS|   |   |   |   |   |   |   |   |PHY|

请注意,周期 ID 会在不同的日子重复出现。

您可以使用条件聚合:

select room_id,
       max(case when day = 1 then slot_1 end) as day_1_slot_1,
       max(case when day = 1 then slot_2 end) as day_1_slot_2,
       . . . 
       max(case when day = 2 then slot_1 end) as day_2_slot_1,
       max(case when day = 2 then slot_2 end) as day_2_slot_2,
       . . . 
from schedule s
group by room_id

虽然不声称是最终解决方案,但规范化设计可能如下所示。坦率地说,如果说现在的设计比这更合适,那就有点难以置信了。

+--------+-----+------+---------+
| roomid | day | slot | subject |
+--------+-----+------+---------+
|      1 |   1 |    1 | BIO     |
|      2 |   1 |    2 | BIO     |
|      1 |   2 |    2 | CHE     |
|      2 |   2 |    2 | CHE     |
|      1 |   4 |    3 | KIS     |
|      2 |   4 |    3 | KIS     |
|      2 |   3 |    5 | ENG     |
|      1 |   3 |    6 | ENG     |
|      1 |   5 |    6 | PHY     |
|      2 |   5 |    6 | PHY     |
+--------+-----+------+---------+