window 函数的 PostgreSQL array_agg 顺序

PostgreSQL array_agg order for window functions

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

除了我想 array_agg 通过 window 函数:

 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||...
                                    ^

我可能应该从子查询中进行选择,就像上面引用的问题的第一个答案所建议的那样。我希望得到像 order by 这样简单的东西(在那个问题的第二个答案中)。或者也许我只是懒惰查询,应该做 group by 而不是 select distinct.

我确实尝试在 windowing 函数 (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/ 如果你恰好对我从哪里得到医学词汇表感到好奇)

是的,看起来我确实是糊涂了,不需要 window 功能。这似乎有效:

 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

我暂时不会接受我的回答,因为它只是回避问题而不是实际回答问题,并且有人可能会就此事说些更有用的东西。

像这样:

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;