简体   繁体   中英

Combining multiple rows in postgreSQL into one row?

I'm new to postgreSQL. My goal is to run a query that returns all the item_id's listed for each proposal_id, where each unique proposal_id is a separate row entry, and each item_id is a column in that row entry.

Table 1 data looks like this:

proposal_id    item_id  

1              83054
1              81048
2              71384
2              24282
2              19847
2              18482
3              84720
4              18081
4              73018

Here's what I want it to look like:

proposal_id     item_id_1     item_id_2    item_id_3    item_id_4    item_id_n
1                  83054      81048
2                  71384      24282        19847        18482
3                  84720
4                  18081      73018

The challenge is that I can have the same proposal_id for anywhere between 1 and up to 11 or more entries.

This is a simplified version for the purposes of asking this question. Once I nail this, my plan is to then join additional data for each item_id and proposal_id from other tables in here.

Any help greatly appreciated.

Thanks!

EDITED: Fixed table aesthetics

First, determine how many columns you need:

select proposal_id, array_length(array_agg(item_id), 1)
    from the_table
    group by 1
    order by 2 desc
    limit 1

Next, execute the following query with sufficient number of a's.

select proposal_id, a[1] id1, a[2] id2, a[3] id3, a[4] id4
from (
    select proposal_id, array_agg(item_id) a
    from the_table
    group by 1
    order by 1) z

SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM