Vertica: how can you concate values by some order?
Asked Answered
S

1

0

Suppose you have columns

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

and you want the columns concatenated such that the end result would look like

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 

where you want to get the col values in Descending order within the new column ABC_value_DESC and then return corresponding name of column in the new column ABC_value_DESC_colnames.

How can you do the concatenation of values of multiple columns into a new column in Descending order and return column names by value order (not name order) in Vertica 9?


Ps. I have tried Listagg -function but bugs such that ordering not implemented and when tried Vertica's suggestion here giving false result and even bugs with alternative here.

Salmonberry answered 26/4, 2019 at 10:58 Comment(1)
LISTAGG() - as clearly described in the fine manual - is an AGGREGATE FUNCTION. Something you should use with a GROUP BY. By reading the three rows example here above it looks like you'er talking about string (?) Concatenation. As far as I can see LISTAGG() works exactly as expected.Preceptor
S
1

You can do this with a nasty case expression. For three columns it is not so bad:

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;

This particular version assumes there are no duplicates or NULL values, although this can be adopted for that purpose.

Standup answered 26/4, 2019 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.