【问题标题】:How to order a string aggregation based on another column in postgresql?如何根据 postgresql 中的另一列对字符串聚合进行排序?
【发布时间】:2018-07-11 08:50:20
【问题描述】:

所以基本上我有 2 个多边形表 tableA,我想用来自 tableB 的聚合字符串来更新它们。 tableB 有 2 列

TableB 的结构类似于

viable | fruit_id
yes    | banana1
no     | apple2
maybe  | watermelon1
no     | peach3

我的更新查询如下所示:

update TableA a set
    fruitids = (select string_agg(fruit_id, ', ' order by fruit_id)
                from tableB b st_contains(b.geom, a.geom))

但这只会按字母顺序返回水果 ID。我怎样才能使它首先列出可行的?在这种情况下,我的预期输出是:

banana1, watermelon1, apple2, peach3

【问题讨论】:

  • 您不应该存储逗号分隔的值开始。规范化您的模型并在 tablea 和 tableb 之间创建适当的多对多关系
  • @a_horse_with_no_name 我很欣赏数据问题,但如果我与这​​两个表创建多对多关系,那么我很容易拥有超过 1 亿行。本质上,我需要人们查看列开头的可行记录,如果它不好,那么他们需要检查记录中的 2-8 个其他字符串。这就是为什么我需要你或其他 SQL Jedi 大师的 SQL 执行智慧

标签: sql postgresql sql-order-by string-aggregation


【解决方案1】:

你可以使用条件排序:

select string_agg(fruit_id, ', ' order by 
                                   case viable
                                      when 'yes' then 1 
                                      when 'maybe' then 2
                                      else 3 
                                   end, 
                                   fruit_id)
from tableB b st_contains(b.geom, a.geom)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 2021-09-26
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多