2016-04-27 107 views
1

我有这样的表。字符串聚合组和计数值

| table      | 
| class_id| name | gender | 
+---------+---------+----------+ 
|  1 | Jane |  F | 
|  1 | John |  M | 
|  1 | Tom  |  M | 
|  1 | Bob  |  M | 
|  2 | Jack |  M | 
|  2 | Kate |  F | 

我有这样的查询。

select id, array_to_string(array_agg(name), ' - '::text) as name_list from table 
group by class_id 

我的结果是

| 1 | Jane-John-Tom-Bob | 

,但我想算我的性别也算我的意思是在第一组(CASS 1)我需要像1 F + 3M的

我的要求是这样的,我想在1组中使用它。

| 1 | Jane-John-Tom-Bob |1F + 3M 
+2

'array_to_string(ARRAY_AGG(名称), ' - '::文)'可以简化为'string_agg(名字,' - ')' –

回答

2

你可以做到这一点与过滤汇总:

select id, 
     string_agg(name), ' - ') as name_list, 
     concat( 
      count(*) filter (where gender = 'F'), 
      'F + ', 
      count(*) filter (where gender = 'M'), 
      'M') as gender_count 
from table 
group by class_id; 

如果你是在一个旧的Postgres版本,则需要更换

count(*) filter (where gender = 'F') 

count(case when gender = 'F' then 1 end) 

(和'M'相同)

+0

感谢您的帮助。那很棒。为了进一步的使用,如果我不知道值,但我知道一列,我可以用于组如何在过滤器中使用它?也许我可以使用超过10个过滤器值。 – lokmancetin

+0

@lokmancetin:抱歉,我不了解你。您分组的列与您在 –

+0

上应用已过滤聚合的列无关。在您的答案中,过滤器值常见于F和M. Simple。但是,如果过滤器值超过50,那么该值如何也在本表中的列中。我可以通过组获得他的值,我想在过滤器聚合中使用这些组合值。 – lokmancetin

0

还有不使用过滤器集合体

select tt.class_id, string_agg (t, ','::text) as gender, string_agg(distinct y,','::text) as name 

from 

(

select class_id, count(gender)::text|| string_agg(distinct gender, ',' ) as t 
     from string_test 
group by class_id , gender 

) tt , 

(
select class_id, string_agg(distinct name::text, ','::text) as y 
    from string_test 
group by class_id 
) yy 
where tt.class_id=yy.class_id 

group by tt.class_id 

结果的另一解决方案;

+==========+========+===================+ 
| class_id | gender | name    | 
+==========+========+===================+ 
| 1  | 1F,3M | Bob,Jane,John,Tom | 
+----------+--------+-------------------+ 
| 2  | 1F,1M | Jack,Kate   | 
+==========+========+===================+