[英]Presto SQL pivoting (for lack of a better word) data
我正在使用Presto數據庫中的一些課程數據。 表中的數據如下所示:
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
我知道我可以通過在每個時間段內加入表來做到這一點,但是我想問一下這里是否有專家建議使用更具可擴展性的解決方案(例如,不必在每個時間段內手動創建新的連接) )。 有什么建議么?
您可以只使用條件聚合:
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.