John Ruddell
John Ruddell

Reputation: 25842

Postgres pivot results with no unique identifier to group by

I'm having a little trouble pivoting this query... Usually there is an identifier or something common to group the data, but in this particular case there isn't, any help is appreciated!

lets say i have a sample table like so

CREATE TABLE test (
    id text primary key,
    created_at date not null default CURRENT_DATE
);

INSERT INTO test (id) VALUES
('AS00334455'),
('AS009988'),
('AS0011223'),
('AS00908800'),
('PS00555555'),
('PS00333333'),
('PS00444444');

visually it would look like this

|         id | created_at |
|------------|------------|
| AS00334455 | 2018-07-05 |
|   AS009988 | 2018-07-05 |
|  AS0011223 | 2018-07-05 |
| AS00908800 | 2018-07-05 |
| PS00555555 | 2018-07-05 |
| PS00333333 | 2018-07-05 |
| PS00444444 | 2018-07-05 |

I'd like to select results from this table where i get the ID column pivoted by the first 2 characters of the ID. visually that would look like this

|         AS |         PS |
|------------|------------|
| AS00334455 | PS00555555 |
|   AS009988 | PS00333333 |
|  AS0011223 | PS00444444 |
| AS00908800 |            |

what i tried so far was this, but im stuck on what group by to apply to render the results appropriately

SELECT
  MAX(case when t.id_type = 'AS' then t.id else '' end) as AS,
  MAX(case when t.id_type = 'PS' then t.id else '' end) as PS
FROM
(  SELECT LEFT(id, 2) as id_type, id
   FROM test
) as t;

I could probably use a row count and nest inside another select, but im concerned about performance as the real table is already a few million records and there are a lot of other things happening in this query. So optimization is key

Fiddle to play around with

Upvotes: 0

Views: 220

Answers (1)

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48177

This is one option SQL DEMO:

WITH cte as (
  SELECT ROW_NUMBER() OVER (PARTITION BY LEFT(id, 2) ORDER BY id) as rn,
         LEFT(id, 2) as id_type, id             
  FROM test  
)
SELECT MAX( CASE WHEN id_type = 'AS' THEN id END) as "AS",
       MAX( CASE WHEN id_type = 'PS' THEN id END) as "PS"
FROM cte
GROUP BY rn
ORDER BY rn
;

OUTPUT

|         AS |         PS |
|------------|------------|
|  AS0011223 | PS00333333 |
| AS00334455 | PS00444444 |
| AS00908800 | PS00555555 |
|   AS009988 |     (null) |

Upvotes: 1

Related Questions