如何在不创建存储过程的情况下在oracle中实现以下功能?
Data Set:
question_id element_id
1 7
1 8
2 9
3 10
3 11
3 12
Desired Result:
question_id element_id1 element_id2 element_id3
1 7 8 null
2 9 null null
3 10 11 12
答案 0 :(得分:1)
这是一个数据透视查询,但您需要一个透视列。这就是row_number()
的用武之地:
select question_id,
max(case when seqnum = 1 then element_id end) as element_id1,
max(case when seqnum = 2 then element_id end) as element_id2,
max(case when seqnum = 3 then element_id end) as element_id3
from (select t.*,
row_number() over (partition by question_id order by element_id) as seqnum
from t
) t
group by question_id;