我有一个由三个表组成的PostgreSQL数据库结构
表格定义:
CREATE TABLE separabilities (
data_bands integer[] NOT NULL,
thematic_class1 integer NOT NULL,
thematic_class2 integer NOT NULL,
jm_dist double precision NOT NULL )
CREATE TABLE thematic_classes (
id integer NOT NULL,
file_name text NOT NULL )
CREATE TABLE data_bands (
id integer NOT NULL,
file_name text NOT NULL,
band integer NOT NULL )
我想要的是一个查询,它给出了按data_bands分组的平均分隔率,以及一个数组,其中实际的文件名和条带对应于data_bands数组中的分离元素。
如果没有与文件名的连接,查询就会起作用,如下所示:
select
sep.data_bands,
sum(sep.jm_dist)/count(sep.data_bands) as avarage_jm_dist
from separabilities as sep
group by sep.data_bands
order by avarage_jm_dist
结果的示例行: {10,11}; 0,7654
我需要的是: {10,11}; {filename1:bandnumber,filename2:bandnumber}; 0,7654
答案 0 :(得分:0)
步骤1.展开data_bands
,将row_number
添加到avarage_jm_dist
以区分连续的sep
条目:
select
unnest(sep.data_bands) as bands,
array[sep.jm_dist/array_length(sep.data_bands, 1),
row_number() over (order by sep.jm_dist)] as avarage_jm_dist
from separabilities as sep
步骤2.根据未加载的data_bands
加入bands
,并将结果汇总到按avarage_jm_dist
分组的数组
select
array_agg(sub.bands) as bands,
array_agg(b.file_name|| ' : '|| b.band) as file_names,
avarage_jm_dist[1]
from (
select
unnest(sep.data_bands) as bands,
array[sep.jm_dist/array_length(sep.data_bands, 1),
row_number() over (order by sep.jm_dist)] as avarage_jm_dist
from separabilities as sep
) sub
join data_bands b on b.id = bands
group by avarage_jm_dist
order by avarage_jm_dist
注意1.我更改了错误的
sum(sep.jm_dist)/count(sep.data_bands)
到
sep.jm_dist/array_length(sep.data_bands, 1)
因为第一个表达式总是给出sep.jm_dist
。
注意2.如果row_number
中有两个(或更多)行具有相同的separabilities
,则会添加avarage_jm_dist
。