Oracle SQL折叠数据行

时间:2018-06-21 22:16:47

标签: sql oracle group-by

查询的数据当前返回如下:

UserName        Op1        Op2        Op3
--------        ---        ---        ---
 User1           1          0          0
 User2           1          1          1
 User3           1          1          0

结果应该只是一行:

Ops1                    Ops2               Ops3
----                    ----               ----
User1, User2, User3     User2, User3       User2

如何在Oracle中做到这一点?

2 个答案:

答案 0 :(得分:2)

这是一种方法-使用LISTAGG()(我相信它需要Oracle 11.2或更高版本):

with
  test_data ( username, op1, op2, op3 ) as (
    select 'User1', 1, 0, 0 from dual union all
    select 'User2', 1, 1, 1 from dual union all
    select 'User3', 1, 1, 0 from dual
  )
select listagg(case op1 when 1 then username end, ',') 
                               within group (order by username) as ops1,
       listagg(case op2 when 1 then username end, ',') 
                               within group (order by username) as ops2,
       listagg(case op3 when 1 then username end, ',')
                              within group (order by username) as ops3
from   test_data
;

OPS1               OPS2               OPS3              
------------------ ------------------ ------------------
User1,User2,User3  User2,User3        User2 

答案 1 :(得分:1)

如果数字为1,则可以使用DECODE()输出用户名,否则为空词。将名称与LISTAGG()串联。

SELECT LISTAGG(DECODE(OP1, 1, USERNAME, ''), ',') WITHIN GROUP (ORDER BY USERNAME) OPS1,
       LISTAGG(DECODE(OP2, 1, USERNAME, ''), ',') WITHIN GROUP (ORDER BY USERNAME) OPS2,
       LISTAGG(DECODE(OP3, 1, USERNAME, ''), ',') WITHIN GROUP (ORDER BY USERNAME) OPS3
       FROM ELBAT;

db<>fiddle