Assuming your jobs column is a comma separated list of data type text
(or similar) - separated by ', '
- I convert it to an array with string_to_array()
and then unnest()
it to separate rows:
SELECT hour, unnest(string_to_array(jobs, ', ')) AS job
FROM tbl
ORDER BY 1;
You could also use regexp_split_to_table(jobs, ', ')
, which is simpler but does not scale as well with longer strings.
Related questions:
In Postgres 9.3 or later, use a LATERAL
join instead. Assuming the query is simple and jobs is defined NOT NULL
, this works and typically return jobs according to the original order of elements:
SELECT hour, job
FROM tbl, unnest(string_to_array(jobs, ', ')) job -- implicitly LATERAL
ORDER BY 1;
SQL Fiddle.
For more complex queries or if jobs
can be NULL
:
SELECT hour, job
FROM tbl
LEFT JOIN LATERAL unnest(string_to_array(jobs, ', '))
WITH ORDINALITY AS j(job, ord) ON TRUE
ORDER BY hour, ord;
WITH ORDINALITY
requires Postgres 9.4 is only needed to guarantee original order of array elements. Details: