Skip to content
Advertisement

How to add counter id column based on several columns on SELECT query Postgresql

I would like to create a column with counter number based on question_id and matrix_question_id this is my query:

and this is the result

I would like to create a new column as id_counter represent id counter base on question_id and matrix_question_id and I wish the result like this

Advertisement

Answer

What you need here is DENSE_RANK, you can place this next to your row_number:

Further points:

  1. If there is no chance that the two halves of the query can overlap, the UNION ALL will be more efficient than UNION
  2. The row_number is non-deterministic and may return different results each time. You should add an extra ordering clause, perhaps question_id, matrix_question_id, user_input_id or some other unique combination.
  3. ORDER BY on the results of a derived table, view or CTE is not guaranteed to work (unless you are using it with LIMIT, or inside a ranking or window function). You should only place on the very outside of your query.
  4. The very first TempTable seems pointless, you could merge it all directly inside your CTE.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement