Listagg函数在子查询中不起作用

时间:2017-11-08 04:59:30

标签: sql plsqldeveloper

Listagg函数在子查询中使用时不起作用,尽管在prod列中使用listagg函数并不连接单行中的所有产品

select
    a.id,
    a.num,
    (listagg(c.prod_name,',') within group(order by prod_name)
from product c
where c.prod_id = NVL(b.prod_id,b.prod_pos) As prod
from master a, base_product b
where
    b.id = a.id and
    b.type = 1 and
    a.id = 12345;

2 个答案:

答案 0 :(得分:0)

select子句中的子查询缺少select关键字,这可能是错误的直接来源。但是,我们可以改进您的查询,而是加入一个执行聚合的子查询:

select
    a.id,
    a.num,
    coalesce(c.prod, 'NA') as prod
from master a
inner join base_product b
    on b.id = a.id
left join
(
    select listagg(prod_name, ',') within group(order by prod_name) as prod
    from product
) c
    on c.prod_id = NVL(b.prod_id, b.prod_pos) 
where
    b.type = 1 and
    a.id = 12345;

除了重新调用listagg之外,我还使用显式inner join替换了隐式连接语法。这是编写查询的首选方式,这种风格是25年前ANSI SQL标准的一部分。

答案 1 :(得分:0)

您可以在cte或派生表中的listagg(prod, ',') within group(ORDER BY prod)列上使用group by,并将其加入主表,以获取num,如下所示。

id

OR

SELECT t2.id,
       t2.num,
       t1.prod
FROM
  (SELECT num,
          listagg(prod, ',') within group(
                                          ORDER BY prod) AS prod
   FROM table1
   GROUP BY num ) t1
JOIN table1 t2 ON t1.num = t2.num
order by t2.id\\

给你样本数据:

WITH t1 AS
  (SELECT num,
          listagg(prod, ',') within group(
                                          ORDER BY prod) AS prod
   FROM table1
   GROUP BY num)
SELECT t2.id,
       t2.num,
       t1.prod
FROM t1
JOIN table1 t2 ON t1.num = t2.num
ORDER BY t2.id\\

<强>结果:

ID  NUM         PROD
--------------------
101 1701A001    book
102 1701A001    data
103 1702B005    bat
104 1702B005    ball
105 1703C006    Stumps

<强> DEMO