Skip to content
Advertisement

PostgreSQL query: obtain concise string of numbers

Obtain a concise string of the numbers, for example, given 1,2,3,6,7,8,9,12,14, we expect 1-3,6-9,12,14.

Here is the Table:

Use Table tt8, Here is what the result should look like:

Here is what I have so far, but it’s giving me type error. I don’t think this is the correct way.

Advertisement

Answer

You can use a gaps-and-islands approach and then aggregation. The following gets the groups:

You can then put them into a single string:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement