没有唯一标识符可分组的 Postgres 数据透视结果

Postgres pivot results with no unique identifier to group by

我在转换此查询时遇到了一些麻烦...通常有一个标识符或一些共同的东西来对数据进行分组,但在这种特殊情况下没有,任何帮助表示赞赏!

假设我有一个样本 table 就像这样

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');

视觉上看起来像这样

|         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 |

我想从这个 table 中得到 select 结果,其中我得到了由 ID 的前 2 个字符旋转的 ID 列。视觉上看起来像这样

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

到目前为止我尝试的是这个,但我坚持应用哪个组来适当地呈现结果

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;

我可能会使用行计数并嵌套在另一个 select 中,但我担心性能,因为真正的 table 已经有几百万条记录,并且还有很多其他事情正在发生在这个查询中。所以优化是关键

Fiddle to play around with

这是一个选项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
;

输出

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