问题
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.
回答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.
来源:https://stackoverflow.com/questions/55866171/vertica-how-can-you-concate-values-by-some-order