简体   繁体   English

Postgres C 扩展数据类型定义

[英]Postgres C extended data type definition

When dealing with the following problems, Postgres is a bit tricky to deal with more complex structures.在处理以下问题时,Postgres 处理更复杂的结构有点棘手。 I want to set up a two-dimensional array of structure, but I don't know how to make Postgres C support me to do so?我想设置一个二维数组的结构,但是不知道如何让Postgres C支持我这样做? Do anyone have any ideas?有人有什么想法吗?

Table
    id     contents(text)              num(double)
    1       I love you.            {1,3,4,5,6,7,8,10}
    2       why do it?             {3,4,2,11,12,33,44,15}
    3       stopping.              {22,33,11,15,14,22,11,55}
    4       try it again.          {15,12,11,22,55,21,31,11}

Sort the rows of each position of the array to get the fo.lowing structure.对数组中每个 position 的行进行排序,得到如下结构。 The result of the first row below is the first position of the num field column array, and so on.the count 4 refers to returning the first n sorted.下面第一行的结果是num字段列数组的第一个position,以此类推。count 4是指返回排序后的前n个。

select my_func(contents, num, 4) from table;

expected result:预期结果:

                           result
{('stopping.', 22), ('try it again.', 15), ('why do it?', 3), ('I love you.', 1)}
{('stopping.', 33), ('try it again.', 12), ('why do it?', 4), ('I love you.', 3)}
{('stopping.', 11), ('try it again.', 11), ('I love you.', 4), ('why do it?', 2)}
......
......

Thanks in advance.提前致谢。

I'm not sure why you need C extended data type, but the following will give you what you want and can be implemented as plpgsql function.我不确定您为什么需要 C 扩展数据类型,但以下将为您提供您想要的并且可以实现为 plpgsql function。

WITH t1 AS (
  SELECT id, contents, unnest (num) AS n FROM table
),
t2 AS (
  SELECT id, contents, n,
         row_number () OVER (PARTITION BY id ORDER BY id) AS o
         FROM t1 ORDER BY o ASC, n DESC, id ASC
),
t3 AS (
  SELECT array_agg (ROW (contents, n)) AS a, o
         FROM t2 GROUP BY o ORDER BY o
)
SELECT array_agg (a ORDER BY o) FROM t3;

UPDATE: Problem of the above may be undefined order of 'unnest'.更新:上述问题可能是“unnest”的未定义顺序。 The following gives consistent relation between index and num, but need to write the size of num array explicitly.下面给出 index 和 num 的一致关系,但需要明确写出 num 数组的大小。

WITH RECURSIVE t1 (i, id, contents, num) AS (
  SELECT 1, id, contents, num[1] FROM table
  UNION ALL
  SELECT t1.i + 1, table.id, table.contents, table.num[t1.i + 1]
         FROM t1, table
         WHERE t1.id = table.id AND t1.i < 8 -- put here size of array
),
t2 (i, d) AS (
  SELECT i, array_agg (ROW (contents, num) ORDER BY num DESC)
         FROM t1 GROUP BY i
)
SELECT array_agg (d ORDER BY i) FROM t2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM