0

Grouping col_1 in ascending values of seq column to display values from comment columns in multiple columns for below sample data:

col_1  |  Seq  |  Comment |
--------------------------|
ABC    |   30  |  TestC   |
ABC    |   50  |  TestE   |
ABC    |   80  |  TestG   |
ABC    |   10  |  TestA   |
ABC    |   60  |  TestF   |
ABC    |   20  |  TestB   |
ABC    |   70  |  TestF   |
ABC    |   40  |  TestD   |
DEF    |   20  |  TestB   |
DEF    |   10  |  TestA   |
GHI    |   10  |  TestA   |
--------------------------|

Expected output of sql should be:
Col_1  | Col_2 | Col_3 | Col_4 | Col_5 | Col_6 | Col_7 | Col_8 | 
-------|-------|-------|-------|-------|-------|-------|-------|
ABC    | TestA | TestB | TestC | TestD | TestE | TestF | TestG |
DEF    | TestA | TestB |       |       |       |       |       |
GHI    | TestA |       |       |       |       |       |       |
-------|-------|-------|-------|-------|-------|-------|-------|

2 Answers 2

1

You can use conditional aggregation and row_number():

select col_1,
       max(case when seqnum = 1 then comment end) as col_2,
       max(case when seqnum = 2 then comment end) as col_3,
       max(case when seqnum = 3 then comment end) as col_4,
       . . .
from (select t.*,
             row_number() over (partition by col_1 order by seq) as seqnum
      from t
     ) t
group by col_1;
Sign up to request clarification or add additional context in comments.

2 Comments

By using CASE or DECODE, it unnecessarily uses huge lines of code. I want to avoid hard-code kind of coding and use advanced features of SQL. Even a procedure will help.
@RinkuGautam . . . This answers the question that you asked. If you have another question, you should ask it as a question.
0

This basically uses the same row_number function used in Gordon's answer, but for a PIVOT clause.

SELECT *
FROM (
    SELECT t.COL_1
        ,t.comments
        ,row_number() OVER (
            PARTITION BY col_1 ORDER BY seq
            ) AS seqnum
    FROM t
    ) t
PIVOT(MAX(comments) FOR seqnum IN (1 as col_2,2 as col_3,3 as col_4,
                                   4 as col_5,5 as col_6,6 as col_7,
                                   8 as col_8));

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.