假设你有列
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中的值顺序(不是名称顺序)返回列名?
PS。我已经尝试了Listagg -function但是错误,这样订购没有实现,当尝试Vertica的建议here给出错误的结果,甚至错误与替代here。
你可以用令人讨厌的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
值,虽然这可以用于此目的。