PostgreSQL array_agg用于窗口函数的顺序

时间:2016-03-14 10:25:30

标签: postgresql array-agg

我的问题的答案几乎就在这里:PostgreSQL array_agg order

除了我想在窗口函数上使用array_agg:

 select distinct c.concept_name, 
        array_agg(c2.vocabulary_id||':'||c2.concept_name 
                  order by c2.vocabulary_id, c2.concept_name) 
            over (partition by ca.min_levels_of_separation), 
        ca.min_levels_of_separation
 from concept c
 join concept_ancestor ca on c.concept_id = ca.descendant_concept_id 
      and max_levels_of_separation > 0
 join concept c2 on ca.ancestor_concept_id = c2.concept_id 
 where 
 c.concept_code = '44054006'
 order by min_levels_of_separation;

所以,也许这可以在将来的某个版本中使用,但是我收到了这个错误

 ERROR:  aggregate ORDER BY is not implemented for window functions
 LINE 2: select distinct c.concept_name, array_agg(c2.vocabulary_id||...
                                    ^

我应该从子查询中选择,就像上面引用的问题的第一个答案所暗示的那样。我希望有一些简单的顺序(在那个问题的第二个答案中)。或者我可能只是对查询很懒惰而应该使用group by代替select distinct

我确实尝试在窗口函数(over (partition by ca.min_levels_of_separation order by c2.vocabulary_id, c2.concept_name))中输入顺序,但是我得到了这样的重复行:

 "Type 2 diabetes mellitus";"{"MedDRA:Diabetes mellitus"}";1
 "Type 2 diabetes mellitus";"{"MedDRA:Diabetes mellitus","MedDRA:Diabetes mellitus (incl subtypes)"}";1
 "Type 2 diabetes mellitus";"{"MedDRA:Diabetes mellitus","MedDRA:Diabetes mellitus (incl subtypes)","SNOMED:Diabetes mellitus"}";1

(顺便说一下:http://www.ohdsi.org/如果您对我获得医学词汇表的位置感到好奇)

2 个答案:

答案 0 :(得分:0)

是的,它确实看起来像是一团糟,不需要窗口功能。这似乎有效:

 select  c.concept_name, 
         array_agg(c2.vocabulary_id||':'||c2.concept_name 
                   order by c2.vocabulary_id, c2.concept_name), 
         ca.min_levels_of_separation
 from concept c
 join concept_ancestor ca on c.concept_id = ca.descendant_concept_id 
      and max_levels_of_separation > 0
 join concept c2 on ca.ancestor_concept_id = c2.concept_id
 where c.concept_code = '44054006'
 group by c.concept_name, ca.min_levels_of_separation
 order by min_levels_of_separation

我暂时不会接受我的回答,因为它只是避免了问题,而不是实际回答问题,而且有人可能会对这个事情说些更有用。

答案 1 :(得分:0)

像这样:

select distinct c.concept_name, 
    array_agg(c2.vocabulary_id||':'||c2.concept_name ) over (partition by ca.min_levels_of_separation  order by c2.vocabulary_id, c2.concept_name), 
    ca.min_levels_of_separation
from concept c
join concept_ancestor ca on c.concept_id = ca.descendant_concept_id 
  and max_levels_of_separation > 0
join concept c2 on ca.ancestor_concept_id = c2.concept_id 
where 
c.concept_code = '44054006'
order by min_levels_of_separation;