【发布时间】:2022-01-23 06:25:13
【问题描述】:
我想将 GroupCount 的键值对数组映射到仅映射特定键的 GroupsResult 复合类型。
我正在使用unnest 将数组转换为行,然后使用 3 个单独的选择语句来提取值。
这感觉就像为这么简单的事情编写了很多代码。
有没有更简单/更简洁的方法来进行从数组类型到GroupsResult 类型的映射?
create type GroupCount AS (
Name text,
Count int
);
create type GroupsResult AS (
Cats int,
Dogs int,
Birds int
);
WITH unnestedTable AS (WITH resultTable AS (SELECT ARRAY [ ('Cats', 5)::GroupCount, ('Dogs', 2)::GroupCount ] resp)
SELECT unnest(resp)::GroupCount t
FROM resultTable)
SELECT (
(SELECT (unnestedTable.t::GroupCount).count FROM unnestedTable WHERE (unnestedTable.t::GroupCount).name = 'Cats'),
(SELECT (unnestedTable.t::GroupCount).count FROM unnestedTable WHERE (unnestedTable.t::GroupCount).name = 'Dogs'),
(SELECT (unnestedTable.t::GroupCount).count FROM unnestedTable WHERE (unnestedTable.t::GroupCount).name = 'Birds')
)::GroupsResult
小提琴
【问题讨论】:
标签: sql postgresql casting composite-types aggregate-filter