如何实现以横向方式显示结果?
如我的数据库中显示,我有3个字段。主题,结果,期间
我计划只创建period1,period2,period3,period4字段
为每个时期节省价值,但我不认为这是不可取的。
sample database:
subject | result | period |
--------------------------------------
eng | 100 | 1 |
lit | 95 | 1 |
eng | 95 | 2 |
lit | 86 | 2 |
eng | 92 | 3 |
lit | 88 | 3 |
subject | period1 | period2 | period3 | period4 |
-----------------------------------------------------------
eng | 100 | 95 | 92 | |
lit | 95 | 86 | 88 | |
hope you can help mo guys. thank you in advance.
答案 0 :(得分:0)
快速直接的解决方案:
select
aggr.subject,
max(aggr.period1),
max(aggr.period2),
max(aggr.period3),
max(aggr.period4)
from (
select
subject as subject,
result as period1,
0 as period2,
0 as period3,
0 as period4
from test
where period = 1
union
select
subject,
0,
result,
0,
0
from test
where period = 2
union
select
subject,
0,
0,
result,
0
from test
where period = 3
union
select
subject,
0,
0,
0,
result
from test
where period = 4
) aggr group by aggr.subject;