-2

I have a table with two columns: care_team and city:

enter image description here

I am trying to pivot these columns so that there is 1 row, and four additional columns. It should look something like this:

enter image description here

This might be super simple but I am in need of help.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
airking94
  • 3
  • 1
  • You never added the code you tried, so I trimmed that dangling remark. Also, for your next question, please remember to disclose your version of Postgres and a proper table definition (`CREATE TABLE` script). And show data as text, never as image. – Erwin Brandstetter May 05 '23 at 01:19

1 Answers1

0

crosstab()

You can pivot with the crosstab() function provided by the additional module tablefunc.

There is fineprint to this, but your question is light on details. In particular, why are your cities ordered the way they are in the result. I assume sorted alphabetically. And I assume there are always 4 cities per team. Else you may need to do more.

SELECT *
FROM   crosstab(
   'SELECT care_team, 1, city
    FROM   tbl
    ORDER  BY care_team, city'  -- needs to be "ORDER BY 1,2" here
   ) AS ct ("Team" text, "1" text, "2"  text, "3" text, "4" text);

fiddle

In-depth instructions here:

Conditional aggregates

One alternative would be with conditional aggregates. That works with standard SQL features, but crosstab() is typically faster.

The specific difficulty of your rump case is that there is no "category" column. So we would have to create one in a subquery, for instance with row_number(). But, based on the same assumptions as above, we can make it work on a single query level with the ordered-set aggregate function percentile_disc():

SELECT care_team AS "Team"
     , percentile_disc (0) WITHIN GROUP (ORDER BY city)
     , percentile_disc (.251) WITHIN GROUP (ORDER BY city)
     , percentile_disc (.501) WITHIN GROUP (ORDER BY city)
     , percentile_disc (.751) WITHIN GROUP (ORDER BY city)
FROM   tbl
GROUP  BY 1;

fiddle

Assuming 4 cities per team, each next value kicks in after an increment of 1/4 ...

See:

Your hidden agenda

You later commented:

... two columns, one column being the team and the other, a string value comprised of all the cities within that team.

That's actually a lot simpler:

SELECT care_team AS "Team", string_agg(city, ', ') AS cities
FROM   tbl
GROUP  BY 1;

fiddle

See:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • To add a little more to this, the cities assigned to the teams can change and the number of cities can change as well and are not always limited to just 4 per team. Some can have 1 and others can have 8 etc. Once pivoted the end result i am desiring is two columns, one column being the team and the other, a string value comprised of all the cities within that team. – airking94 May 05 '23 at 17:50
  • @airking94: You should have said so right away. See added solution. – Erwin Brandstetter May 06 '23 at 02:00