LISTAGG,参考另一列更改结果排序

时间:2018-04-18 05:57:50

标签: sql oracle listagg

我有一张这样的表:

item   Desc
----   ----
CSH    Cash
CHQ    Cheque
CDJ    Cross Department
EPS    EPS

我有这样的SQL:

SELECT LISTAGG(a.item, ', ') WITHIN GROUP (ORDER BY a.item ASC) "item",
LISTAGG(a.Desc, ', ') WITHIN GROUP (ORDER BY a.Desc ASC) "Desc"
FROM tableA a;

,结果如下:

item                 Desc
----                 ----
CDJ,CHQ,CSH,EPS      Cash,Cheque,Cross Department,EPS

然而,我的预期结果是根据'Desc'的排序对'item'进行排序,这意味着:

'CSH,CHQ,CDJ,EPS'

我该怎么办呢?

2 个答案:

答案 0 :(得分:3)

以下是您的问题的解决方案:

SELECT LISTAGG("item", ', ') WITHIN GROUP (ORDER BY "Desc") "item",
LISTAGG("Desc", ', ') WITHIN GROUP (ORDER BY "Desc" ) "Desc"
FROM tableA;

<强>输出:

  item               |     Desc
------------------------------------------------------------
CSH, CHQ, CDJ, EPS   |   Cash, Cheque, Cross Department, EPS

演示链接:

  

http://sqlfiddle.com/#!4/16ed58/10

答案 1 :(得分:0)

listagg的两种用法中使用相同的ORDER BY

SELECT LISTAGG(a.item, ', ') WITHIN GROUP (ORDER BY a.Desc ASC) "item",
       LISTAGG(a.Desc, ', ') WITHIN GROUP (ORDER BY a.Desc ASC) "Desc"
FROM tableA a;