简体   繁体   中英

2 listagg in one SQL Select in Oracle

I have a table in the form of :

| ID    | COURSE | PASS |
---------------------------
| 1     | 1      | 1      |
| 1     | 2      | 1      |    
| 1     | 3      | 1      |
| 1     | 4      | 0      |
| 1     | 5      | 0      |

and I want row in the form:

| ID    | FAILED | PASSED |
---------------------------
| 1     | 4,5    | 1,2,3  |

the only i figured is something like this:

    select NVL(passed.id, failed.id), passed.test, failed.test from 
        (select id, listagg(course, ',') within group (order by course) test from table1 where pass = 1 group by id ) passed 
    full outer join
        (select id, listagg(course, ',') within group (order by course) test from table1 where pass = 0 group by id ) failed
    on passed.id = failed.id

is there a way to do it in a single query ?

Try

select  id, 
  listagg(case when pass = 1 then course end, ',') within group (order by course) passed,
  listagg(case when pass = 0 then course end, ',') within group (order by course) failed
from table1
group by id

Here is a sqlfiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM