有条件地选择PostgreSQL中数组中最常见的值

时间:2017-06-09 10:45:47

标签: postgresql postgresql-9.5

我的PostgreSQL 9.5 db中有一个表(只有一行),有两列,即count(bigint)和array(text)。

 public PropertyAdapter(Context context, List<DataProperty> data){

    Log.e("shared",":test");
    SharedPreferences sharedPreferences =   context.getSharedPreferences("reg_id",Context.MODE_PRIVATE);
    user_id = sharedPreferences.getString("id","");
    this.context=context;
   // inflater= (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.data=data;


    PropertyID        = ((Activity) context).getIntent().getExtras().getString("PropertyID");
    placeId           = ((Activity) context).getIntent().getExtras().getString("placeId");
    property_type     = ((Activity) context).getIntent().getExtras().getString("property_type");
    BuildingName      = ((Activity) context).getIntent().getExtras().getString("BuildingName");
    BedRooms          = ((Activity) context).getIntent().getExtras().getString("BedRooms");
    SenderId          = ((Activity) context).getIntent().getExtras().getString("SenderId");
}

数组表示六个(因此计数= 6)一组值,即count array 6 "112,19.3,142,142,19.3,172,172,20.3,202,202,20.3,232,232,19.3,262,262,19.3,292" Lower_limitValue。现在,我需要有条件地修改我的数组,即,当上限和下限一致时,选择第一个上限和最后一个下限并返回限制中最常见的值(即19.3)。我想要的输出就像:

Upper_limit

有人能帮助我指点一下我想要的输出吗?

1 个答案:

答案 0 :(得分:1)

我必须管理 - 我不明白你如何得到count = 1,但下面是一个如何使用firsrt,last和最常见值构建数组的示例。请注意,如果有几个共同的价值观会不可预测地选择em

t=#
with a(r) as (values(array[112,19.3,142,142,19.3,172,172,20.3,202,202,20.3,232,232,19.3,262,262,19.3,292]))
, p as (select * from a,unnest(a.r) with ordinality)
, t as (
select count(1) over (partition by unnest)
, unnest u
, r[1] a
, r[array_length(r,1)] e
from p
order by unnest
limit 1
)
select array[a,u,e]
from t
;
     array
----------------
 {112,19.3,292}
(1 row)