我希望返回一行合并多行,因此对于示例表:
ID | VAL1 | VAL2
1 | v1 | v2
1 | v3 |v4
我想回复:
ID|VAL1|VAL2|VAL1_1|VAL2_1
1 | v1 | v2 | v3 | v4
其中ID | VAL1 | VAL2 | VAL1_1 | VAL2_1是列标题
我不相信枢轴可以工作,因为值(v1等)可以是任何值。
非常感谢任何帮助
答案 0 :(得分:2)
如果您想要动态数据透视,那么您需要动态SQL。但是,你可以通过条件聚合做你想做的事情:
select id,
max(case when seqnum = 1 then val1 end) as val1,
max(case when seqnum = 1 then val2 end) as val2,
max(case when seqnum = 2 then val1 end) as val1_1,
max(case when seqnum = 2 then val2 end) as val2_1
from (select t.*, row_number() over (partition by id order by id) as seqnum
from t
) t
group by id;
如果您的行以特定方式排序,则应修改order by
。