0

Input

question_id option_rank
1 1
1 2
2 1
2 2
2 3

How to get below output using SQL. Position will be new fabricated column in the output. Basically a given option rank to be repeated n times, n being max option rank of a given question.

question_id option_rank position
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3

Created numbers table with single column consisting of id from 1 to 1000(1000 rows) and then joined it with above question table.

Mohammed
  • 1
  • 1

1 Answers1

0

We can use a self join here:

SELECT t1.question_id, t1.option_rank, t2.option_rank AS position
FROM yourTable t1
INNER JOIN yourTable t2
    ON t2.question_id = t1.question_id
ORDER BY 1, 2, 3;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360