在Oracle中选择一个SQL中的2个listagg

时间:2013-07-14 13:07:00

标签: sql oracle aggregate-functions

我有一张表格:

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

我想在表单中输入行:

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

唯一的想法是这样的:

    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

有没有办法在单个查询中执行此操作?

1 个答案:

答案 0 :(得分:10)

尝试

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