首先,您需要添加提供此功能的模块。tablefunc
CREATE EXTENSION tablefunc;
现在你需要这样的查询,
SELECT *
FROM crosstab(
-- here we normalize this into `id | cat | value`
-- where the category is [1-3]
$$SELECT id, RIGHT(name,1)::int AS cat, name AS value FROM foo ORDER BY 1,2;$$,
-- For just the cat 1,2,3
$$VALUES (1),(2),(3);$$
) AS ct(id text, name1 text, name2 text, name3 text);
这将返回这个,
id | name1 | name2 | name3
----+---------+---------+---------
1 | name1.1 | name1.2 | name1.3
2 | name2.1 | name2.2 |
3 | name3.1 | |
(3 rows)
请注意这里的大问题,您的类别实际上是您的数据的函数RIGHT(name,1)::int
。那可能是你的坚持。相反,您提供的实际数据category
似乎可以完全忽略,除非我遗漏了什么。
另请注意,我在两个地方对类别名称进行了硬编码,
$$VALUES (1),(2),(3);$$
和,
ct(id text, name1 text, name2 text, name3 text);
这是必需的,因为 PostgreSQL 不允许您在运行命令时返回结果集未知的查询。这将仅支持[name1 - name3]
如果您希望它真正动态,则程序的范围会扩大很多,并且在这个问题上是题外话。