在尝试旋转 sql 表时,我遇到了这篇文章 Here 。通过使用这种方法,我创建了一个查询。但是我现在意识到它当然会使用 MAX 函数聚合结果。但是,我需要 Colum 进行旋转,但要显示所有事件。代码取自上面的帖子。
SELECT dy,
MAX(CASE WHEN period = 1 THEN subj ELSE NULL END) AS P1,
MAX(CASE WHEN period = 2 THEN subj ELSE NULL END) AS P2,
FROM Classes
GROUP BY dy
所以本质上我希望使用它但没有 max 函数?有任何想法吗?
编辑示例数据
Day Period Subject
Mon 1 Ch
Mon 2 Ph
Tue 1 Ph
Tue 2 Ele
Mon 1 Ch
Mon 2 Ph
Tue 1 Ph
Tue 2 Ele
示例输出
Day P1 P2
Mon Ch Ph
Mon Ch Ph
Tue Ph Ele
Tue Ph Ele
所以基本上如果数据输入两次,它会出现两次......
编辑实际的sql ..
SELECT other
MAX(CASE WHEN period = 1 THEN table2.subj ELSE NULL END) AS P1,
MAX(CASE WHEN period = 2 THEN table2.subj ELSE NULL END) AS P2
FROM table1
left join table2 on table2.ID = subject
GROUP BY other
示例数据
表格1
Dy Period Subject other
Mon 1 1 1
Mon 2 2 1
Tue 1 3 2
Tue 2 4 2
Mon 1 5 3
Mon 2 6 3
Tue 1 7 4
Tue 2 8 4
表2
ID Subj
1 ch
2 ph
3 ph
4 ele
5 ch
6 ph
7 ph
8 Ele
示例输出
Day P1 P2 other
Mon Ch Ph 1
Mon Ch Ph 3
Tue Ph Ele 2
Tue Ph Ele 4