sql - PostgreSQL: How to return a subarray dynamically using array slices in postgresql
问题描述
I need to sum a subarray from an array using postgresql.
I need to create a postgresql query that will dynamically do this as the upper and lower indexes will be different for each array.
These indexes will come from two other columns within the same table.
I had the below query that will get the subarray:
SELECT
SUM(t) AS summed_index_values
FROM
(SELECT UNNEST(int_array_column[34:100]) AS t
FROM array_table
WHERE id = 1) AS t;
...but I then realised I couldn't use variables or SELECT statements when using array slices to make the query dynamic:
int_array_column[SELECT array_index_lower FROM array_table WHERE id = 1; : SELECT array_index_upper FROM array_table WHERE id = 1;]
...does anyone know how I can achieve this query dynamically?
解决方案
不需要子选择,只需使用列名:
SELECT SUM(t) AS summed_index_values
FROM (
SELECT UNNEST(int_array_column[tb.array_index_lower:tb.array_index_upper]) AS t
FROM array_table tb
WHERE id = 1
) AS t;
请注意,不建议在 SELECT 列表中使用 set-returning 函数(unnest)。最好将其放入 FROM 子句中:
SELECT sum(t.val)
FROM (
SELECT t.val
FROM array_table tb
cross join UNNEST(int_array_column[tb.array_idx_lower:array_idx_upper]) AS t(val)
WHERE id = 1
) AS t;
推荐阅读
- python - 在 WSL 中使用 buildozer 创建 kivy android 包
- python - 我将如何获得 JSON 中具有最高(子?)值的行?(Python)
- android - 长时间未动的工作代码,突然抛出 NullPointerException
- python-3.x - 在 3d 索引的 rtree (python) 中,如何在树中创建子节点以及如何查询它们?
- mqtt - mosquitto ACL 限制客户端
- html - 页面加载时,关键帧动画在 Inner-Div 上不起作用
- intellij-idea - 如何在 Pycharm 的运行窗口中隐藏路径位置?
- elasticsearch - Logstash 管道数据未推送到 Elasticsearch
- python - 将函数参数分配给动态创建的同名类的属性时出现 NameError
- python - 如何在窗口内对齐 QPushButton?