【问题标题】:postgresql procedure for fetching top 10%,20% and 30% values of the total values用于获取总值的前 10%、20% 和 30% 值的 postgresql 过程
【发布时间】:2017-05-09 07:20:23
【问题描述】:

我有一个名为 Scoreboard 的表,其中包含一个名为 score 的字段,该字段是一个包含值 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 arraycategory 3 = top 30% values of the total no of values in array
并将其以相同格式放入数组中,即
[category 1 values,category 2 values,category 3 values]

【问题讨论】:

    标签: postgresql stored-procedures


    【解决方案1】:

    应该这样做:

    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
    

    【讨论】:

    • 谢谢,但实际上我希望它在一个过程中,而且我忘了提到该数组在表中,所以我们必须从该表中获取值
    • 你可以将上面的内容包装成sql函数。也请尝试在第一次尝试时提出问题 - 否则我们不会回答问题,而是在这里聊天支持
    【解决方案2】:

    我假设,您有一个表,其中一列作为 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}' );
    

    以下是用于查找您提到的类别的功能。如果您的表中没有任何 id 列 然后您可以使用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();
    

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2012-03-29
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      相关资源
      最近更新 更多