2017-05-09 16 views
1

我有一個名爲記分牌表,其包含一個命名爲得分,其是含有值27,56,78,12,89,77,34,23,90,87,33,55,30,67,76,87,56陣列字段,我想寫一個PostgreSQL過程來取三類
category 1 = top 10% values of the total no of values in array
category 2 = top 20% values of the total no of values in array
category 3 = top 30% values of the total no of values in array
並把它放在一個陣列相同的格式,即
[category 1 values,category 2 values,category 3 values]PostgreSQL的過程中,20%和30%的值

回答

0

水木清華這樣應該做的:

t=# with p as (
    with ntile as (
    with v as (
     select unnest('{27,56,78,12,89,77,34,23,90,87,33,55,30,67,76,87,56}'::int[]) a 
    ) 
    select a,ntile(10) over(order by a desc) 
    from v 
) 
    select distinct string_agg(a::text,',') over (partition by ntile),ntile 
    from ntile 
    where ntile <=3 order by ntile 
) 
select array_agg(concat('category ',ntile,' ',string_agg)) 
from p; 
         array_agg 
------------------------------------------------------------ 
{"category 1 90,89","category 2 87,87","category 3 78,77"} 
(1 row) 

Time: 0.493 ms 
+0

謝謝,但實際上我希望它在過程中加上我忘了提及,數組是表,所以我們必須從該表 – naina

+1

取值你可以用上面的到SQL的功能。也請嘗試從第一次嘗試問問題 - 否則我們不回答問題,而是在此聊天支持 –

0

我假設,你有一個列作爲id和另一個是數組類型的表。基於假設 我已經創建瞭如下表並向其中插入兩個值。

create table test_array (id int, values int[]); 
insert into test_array values(1 ,'{27,56,78,12,89,77,34,23,90,87,33,55,30,67,76,87,56}'); 
insert into test_array values(2 ,'{72,65,84,21,98,77,43,32,9,78,41,66,3,76,67,88,56}'); 

以下是用於查找您所提到的類別的功能。如果你沒有任何標識列在表 ,那麼你可以通過使用window function暗示加號:ROW_NUMBER()。

create or replace function find_category() returns table(category text[]) as 
$$ 
BEGIN 

return query with unnestColumn as (
select id, unnest(values) as values, ntile(10) over(partition by id order by unnest(values) desc) as ntilenumber 
from test_array 
) ,groupedCategory as (select id, ntilenumber, string_agg(values::text,',') as combinedvalues from unnestColumn 
where 
ntilenumber <= 3 
group by id, ntilenumber) 
select array_agg(concat('Categoty',ntilenumber, ' ', combinedvalues)) 
from groupedCategory 
group by id; 

END; 
$$ 
language 'plpgsql'; 

執行下面的函數來檢查輸出。

select * from find_category(); 
相關問題