SQL queries are row based, but you want columns. This requires a pivot. We need something in common for each row so we can group them together. We can add a row_number to each row to put them in order. Then we pivot them into individual columns by grouping by the row number.
with ordered_things as ( select row_number() over(partition by type order by id asc) as rn, id, type from things)select coalesce(max(id) filter(where type = 'ACCOUNT'), '') as account_id, coalesce(max(id) filter(where type = 'CLIENT'), '') as client_id, coalesce(max(id) filter(where type = 'ORDER'), '') as order_idfrom ordered_thingsgroup by rnorder by rn
Since we know there's only one ID for each type in the group, max(id)
is just a way to satisfy the need for each column of a group by query to be an aggregated function.
coalesce
just gets rid of unsightly nulls when there isn't an equal number of ids for each type.