SQL连接其中一列

时间:2016-11-21 15:18:44

标签: sql oracle concatenation listagg

我有以下输出:

portfolio name | accounts | segment | number
A | USD | seg1 | 23
A | CNY | seg2 | null
A | EUR | seg2 | null
B | EUR | seg2 | null
B | USD | seg2 | null
B | EUR | seg3 | 24

我想基本上根据投资组合名称,相同的段和相同的数字连接所有行。正如您所看到的,有时数字也可以为空。

基本上我想要这个例子的最终输出是:

A | USD | seg1 | 23
A | CNY, EUR | seg2 | null
B | EUR, USD | seg2 | null
B | EUR | seg3 | 24

我尝试过使用listagg,但无法弄明白......

希望你理解我的问题。

3 个答案:

答案 0 :(得分:1)

如果您使用的是Oracle(您说过您尝试使用LISTAGG),那么:

SELECT t.portfolio_name, t.segment, 
       LISTAGG(COALESCE(t.accounts,''),',') WITHIN GROUP (ORDER BY t.accounts) as segments,
       (SELECT LISTAGG(COALESCE(s.number,''),',') WITHIN GROUP  (ORDER BY s.number) 
        FROM (SELECT DISTINCT p.portfolio_name,p.segment,p.number
              FROM YourTable p) s
        WHERE t.portfolio_name = s.portfolio_name
          AND t.segment = s.segment ) as numbers
FROM YourTable t
GROUP BY t.portfolio_name, t.segment

答案 1 :(得分:0)

select          "portfolio name"
               ,listagg (accounts,',') within group (order by accounts) as accounts
               ,segment
               ,"number"

from            t

group by        "portfolio name"
               ,segment
               ,"number"
;

答案 2 :(得分:-1)

如果列已修复concat所有列,但请确保为此输出需要将null转换为字符串。 例如:         从t1

中选择c1 +' |' + cast(c2 as varchar)