【问题标题】:Mapping array to composite type to a different row type将数组映射到复合类型到不同的行类型
【发布时间】: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

小提琴

http://sqlfiddle.com/#!17/56aa2/1

【问题讨论】:

    标签: sql postgresql casting composite-types aggregate-filter


    【解决方案1】:

    简单一点。 :)

    SELECT (min(u.count) FILTER (WHERE name = 'Cats')
          , min(u.count) FILTER (WHERE name = 'Dogs')
          , min(u.count) FILTER (WHERE name = 'Birds'))::GroupsResult
    FROM   unnest('{"(Cats,5)","(Dogs,2)"}'::GroupCount[]) u;
    

    db小提琴here

    见:

    细微的区别:如果其中一个名字多次弹出,我们的原始文件会引发异常,而这只会返回最小计数。可能是也可能不是您想要的 - 如果永远不会发生重复,则无关紧要。

    对于许多不同的名称,crosstab() 通常更快。见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多