【问题标题】:Vertica: how can you concate values by some order?Vertica:如何按某种顺序连接值?
【发布时间】:2019-04-26 10:58:43
【问题描述】:

假设你有列

ID | A | B | C
1  | 3 | 1 | 2
2  | 5 | 9 | 1
3  | 1 | 2 | 3 

并且您希望将列连接起来,以使最终结果看起来像

ID | ABC_value_DESC | ABC_value_DESC_colnames
1  | 3,2,1          | A,C,B
2  | 9,5,1          | B,A,C
3  | 3,2,1          | C,B,A 

您希望在新列ABC_value_DESC 中按降序获取col 值,然后在新列ABC_value_DESC_colnames 中返回相应的列名称。

如何在 Vertica 9 中将多列的值以降序顺序连接到新列中并按值顺序(不是名称顺序)返回列名?


附言。我已经尝试过 Listagg -function,但是出现了一些错误,例如未实现排序,并且在尝试 Vertica 的建议 here 时给出了错误的结果,甚至出现了替代 here 的错误。

【问题讨论】:

  • LISTAGG() - 正如精美手册中明确描述的那样 - 是一个聚合函数。您应该与 GROUP BY 一起使用的东西。通过阅读上面的三行示例,您似乎在谈论字符串 (?) 连接。据我所见, LISTAGG() 完全按预期工作。

标签: sql concatenation vertica listagg


【解决方案1】:

你可以用一个讨厌的case 表达式来做到这一点。对于三列来说还不错:

select t.*,
       (gr || ',' ||
        (case when a not in (le, gr) then a
              when b not in (le, br) then b
              else c
         end) || ',' ||
        le
       ),
       ((case gr when a then 'a' when b then 'b' else 'c' end) || ',' ||
        (case when a not in (gr, le) then 'a'
              when b not in (gr, le) then 'b'
              else 'c'
         end) || ',' ||
        (case le when a then 'a' when b then 'b' else 'c' end)
       )          
from (select t.*, greatest(a, b, c) as gr, least(a, b, c) as le
      from t
     ) t;

此特定版本假定没有重复或 NULL 值,尽管可以为此目的采用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    相关资源
    最近更新 更多