[英]Presto SQL pivoting (for lack of a better word) data
I am working with some course data in a Presto database. 我正在使用Presto数据库中的一些课程数据。 The data in the table looks like: 表中的数据如下所示:
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
I would like to format the data so that it looks like: 我想格式化数据,使其看起来像:
student_id 2018_Q1_score 2018_Q1_completed 2017_Q3_score
1 0 N 5
3 4 Y 4
4 2 N 2
I know that I could do this by joining to the table for each time period, but I wanted to ask here to see if any gurus had a recommendation for a more scalable solution (eg perhaps not having to manually create a new join for each period). 我知道我可以通过在每个时间段内加入表来做到这一点,但是我想问一下这里是否有专家建议使用更具可扩展性的解决方案(例如,不必在每个时间段内手动创建新的连接) )。 Any suggestions? 有什么建议么?
You can just use conditional aggregation: 您可以只使用条件聚合:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.