Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 874
Nick Lashinsky Avatar asked Oct 30 '14 22:10

Nick Lashinsky


People also ask

How do I combine values from multiple rows into one row in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

What is crosstab in PostgreSQL?

The crosstab function produces one output row for each consecutive group of input rows with the same row_name value. The output row_name column, plus any “extra” columns, are copied from the first row of the group. The output value columns are filled with the value fields from rows having matching category values.


1 Answers

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

like image 157
klin Avatar answered Nov 03 '22 09:11

klin