| From: | hubert depesz lubaczewski <depesz(at)depesz(dot)com> |
|---|---|
| To: | dfgpostgres <dfgpostgres3(at)gmail(dot)com> |
| Cc: | pgsql-general(at)lists(dot)postgresql(dot)org |
| Subject: | Re: PG Unpivot ? |
| Date: | 2025-11-03 17:22:11 |
| Message-ID: | aQjkwyDjsz8Cgp0X@depesz.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-general |
On Mon, Nov 03, 2025 at 12:18:55PM -0500, dfgpostgres wrote:
> psql (13.2, server 15.3) on linux
>
> I think they call this "unpivot" in MSSQL ?
>
> How can I get an sql query to return one line per column with... an ID,
> column name and value. the ctid for the id field is fine.
>
> Example:
> dvdb=# create table unpivot (intcol integer, floatcol float, strcol
> varchar);
> CREATE TABLE
> dvdb=# insert into unpivot (intcol,floatcol,strcol) values
> (1,1.1,'one'),(2,2.2,'two'),(3,3.3,'three');
> INSERT 0 3
> dvdb=# select * from unpivot;
> intcol | floatcol | strcol
> --------+----------+--------
> 1 | 1.1 | one
> 2 | 2.2 | two
> 3 | 3.3 | three
> (3 rows)
> I want 9 records returned, each row with 3 cols, 1st col is the ctid,
> second is the column name, third is the val.
I think it should work:
select u.ctid, e.* from unpivot u, to_jsonb(u) j, jsonb_each_text(j) e;
Best regards,
depesz
| From | Date | Subject | |
|---|---|---|---|
| Next Message | dfgpostgres | 2025-11-03 17:32:09 | Re: PG Unpivot ? |
| Previous Message | dfgpostgres | 2025-11-03 17:18:55 | PG Unpivot ? |