Search code examples
peewee

Use peewee to flatten rows into columns


database backend is postgresqlon gcp.

I have a group of rows in a table that have an id. I am trying to flatten it out in rows with multiple column.

CREATE TABLE public.lines
(
    line_no int NOT NULL,
    line_content character varying(60) COLLATE pg_catalog."default" NOT NULL,
    parent_id integer NOT NULL,
)

with data

(1,'content 1',parent1)
(2,'content 2',parent1)
(3,'content 3',parent1)
...

Trying to figure out a query to flatten the result to columns,

select line1, line2,line3
where parent='parent1'

How to accompolish this?? THANKS!!!!


Solution

  • This doesn't work. Sql databases are tabular. You can't just arbitrarily return rows that are X-columns wide.

    Your best bet is to use something like Postgres' array_agg which will return an array. Absent that, you could maybe use group_concat or something to produce a comma-separated list.

    But this smells and is probably a horrible idea.

    Just do the collapse/flatten in code if you must.