【问题标题】:Alphabetically order a field with comma separated values按字母顺序排列具有逗号分隔值的字段
【发布时间】:2021-09-15 16:35:31
【问题描述】:

我目前正在处理 Talend 流程,但在订购包含逗号分隔值的字段时遇到问题。这个字段是关于国家的,它可以包含不同的国家。我想知道是否有办法按字母顺序对字段内的这些值进行排序。

我不知道是用 Talend 还是直接用 sql 查询更容易。

以下是该字段的错误值示例:“Portugal,Cabo Verde,Morocco,North Atlantic Ocean, Spain”,如果可能,我希望它按字母顺序排列。

【问题讨论】:

  • 那么您正在寻找的输出究竟是什么?一个新的逗号分隔列表?还是每个元素一行?还是按字母顺序排列的行?
  • 我希望与输入相同,但按字母顺序排序,对于我给出的示例,输出将是:"Cabo Verde,Morocco,North Atlantic Ocean,Portugal,Spain"

标签: postgresql sql-order-by talend comma


【解决方案1】:

这是在 Talend 中的操作方式:

输出将是:

|=--------------------------------------------- ---------------=| |国家 | |=------------------------------------------------ ------------=| |佛得角、摩洛哥、北大西洋、葡萄牙、西班牙| '---------------------------------------------------- -------------'

【讨论】:

    【解决方案2】:

    使用适当的规范化数据模型会容易得多。

    要获得排序后的字符串,您需要先取消嵌套元素,然后将它们聚合回排序后的字符串。

    select other_columns
           (select string_agg(country, ',' order by country)
            from unnest(string_to_array(countries, ',')) as t(country)
           ) as countries_sorted
    from the_table
    

    您可以将其放入一个函数中,让您的生活更轻松:

    create function sort_csv_value(p_input text)
      returns text
    as
    $$
       select string_agg(word, ',' order by word)
       from unnest(string_to_array(p_input, ','));
    $$
    language sql
    immutable;
    

    那么你可以这样使用它:

    select other_columns
           sort_csv_value(countries) as countries_sorted
    from the_table
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2012-11-08
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      相关资源
      最近更新 更多