Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

teradata sql pivot multiple occurrences into additional columns

I have something like this:

ID      Result
1       value1
2       value1
2       value2
3       value1
4       value1
4       value2
4       value3

And I'd like to return something like this:

ID      Result1      Result2      Result3
1       value1
2       value1       value2
3       value1
4       value1       value2       value3

I've searched on pivots and concats and breaks and I just can't find a simple, sensible solution.

TIA

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately Teradata doesn't have a PIVOT function but you can use an aggregate function with a CASE expression to get the result.

select id,
    max(case when seq =1 then result end) result1,
    max(case when seq =2 then result end) result2,
    max(case when seq =3 then result end) result3
from
(
    select id, res, row_number() over(partition by id order by result) seq
    from yourtable
) d
group by id
order by id;

If you have more values for each ID, then you can add more CASE expressions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...