在PostgreSQL中使用数组'where'-statement

时间:2015-07-21 10:47:17

标签: sql arrays postgresql

我有一个由三个表组成的PostgreSQL数据库结构

  • 分离性包含int数组的数据带组合以及更多与此无关的列
  • data_bands 包含将数组中的ID从“可分离性”分配到实际文件和图像带的信息
  • thematic_classes 包含有关'separabilities'中使用的类的信息(不是我的问题的导入)

表格定义:

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

1 个答案:

答案 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