c++ - Postgres C 扩展数据类型定义
问题描述
在处理以下问题时,Postgres 处理更复杂的结构有点棘手。我想建立一个二维数组的结构,但不知道如何让Postgres C支持我这样做?有人有什么想法吗?
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}
对数组中每个位置的行进行排序,得到如下结构。下面第一行的结果是num字段列数组的第一个位置,以此类推。count 4是指返回排序后的前n个。
select my_func(contents, num, 4) from table;
预期结果:
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)}
......
......
提前致谢。
解决方案
我不确定您为什么需要 C 扩展数据类型,但以下内容将为您提供您想要的并且可以作为 plpgsql 函数实现。
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;
更新:上述问题可能是“unnest”的未定义顺序。下面给出 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;
推荐阅读
- sql - 无法解决错误消息 Msg 241, Level 16, State 1, Line 1 从字符串转换日期和/或时间时转换失败
- video-streaming - RTMP 转 WebRTC?是否有意义?
- kotlin - Kotlin 用单引号连接文件内容词
- javascript - Zapier 代码模式:集成 Monday.com
- python - 使用 slackclient 2.x 上传文件
- php - 如何在 oci_bind_by_name 函数中传递 sysdate 来更新记录?
- xml - XSD 断言属性对嵌套元素的相等性?
- r - 如何在 ComplexHeatmap 的连续色标中创建颜色中断?
- c# - Wkhtmltopdf.NetCore 中的分页符
- java - 在 Thymeleaf 中调用 Java 类