查询具有相同不同表的列

时间:2017-11-17 13:44:29

标签: sql oracle

我有两个结构表,如下所示:

THINGS
COLUMNA            COLUMNB
Fruits             Apple
Fruits             Pear
Fruits             Grapes
Dairy products     Yoghurt
.......

QUANTITY
COLUMNC         COLUMND
Fruits           1
Apple            2
Pear             3
Yoghurt          1
Dairy products   1

我需要一个查询来获得类似的内容:

这些方式的COLUMA和COLUMN C:

RESULTA         RESULTB
Fruits          1,2,3
Dairy Products  1

我尝试的查询SQL是:

select COLUMNA, listagg(COLUMND,',') within group (order by COLUMND) from THINGS, QUANTITY  where COLUMNA=COLUMNC group by COLUMNC;

这可能吗?我试图得到这个但无济于事。我正在研究Oracle 12。

1 个答案:

答案 0 :(得分:0)

目前还不清楚如何加入数据,但对于给定的示例,这可行:

select columna result, listagg(columnd, ', ') within group (order by columnd) resultb
  from (select distinct columna, columnd 
          from things t 
          join quantity q on q.columnc in (t.columna, t.columnb))
  group by columna

测试:

with things(columna, columnb) as (
    select 'Fruits',         'Apple'   from dual union all
    select 'Fruits',         'Pear'    from dual union all
    select 'Fruits',         'Grapes'  from dual union all
    select 'Dairy products', 'Yoghurt' from dual ),
quantity(columnc, columnd) as (
    select 'Fruits',          1 from dual union all 
    select 'Apple',           2 from dual union all 
    select 'Pear',            3 from dual union all 
    select 'Yoghurt',         1 from dual union all 
    select 'Dairy products',  1 from dual )
select columna result, listagg(columnd, ', ') within group (order by columnd) resultb
  from (select distinct columna, columnd 
          from things t join quantity q on q.columnc in (t.columna, t.columnb))
  group by columna

结果:

RESULT         RESULTB
-------------- ----------
Dairy products 1
Fruits         1, 2, 3