Presto SQL 旋转(因为缺少更好的词)数据

Presto SQL pivoting (for lack of a better word) data

我正在使用 Presto 数据库中的一些课程数据。 table 中的数据如下所示:

student_id  period   score completed
1           2016_Q1  3     Y
1           2016_Q3  4     Y
3           2017_Q1  4     Y
4           2018_Q1  2     N

我想将数据格式化为:

student_id  2018_Q1_score 2018_Q1_completed 2017_Q3_score
1           0             N                 5
3           4             Y                 4
4           2             N                 2

我知道我可以通过加入每个时间段的 table 来做到这一点,但我想在这里问问是否有专家对更具可扩展性的解决方案提出了建议(例如,也许没有为每个期间手动创建一个新连接)。有什么建议么?

您可以只使用条件聚合:

select student_id,
       max(case when period = '2018_Q1' then score else 0 end) as score_2018q1,
       max(case when period = '2018_Q1' then completed then 'N' end) as completed_2018q1,
       max(case when period = '2017_Q3' then score else 0 end) as score_2017q3
from t
group by student_id