单行子查询返回多行SQL Oracle

时间:2016-12-22 18:43:10

标签: sql oracle

我试图在同一行显示多行。我有以下代码:

SELECT DISTINCT
  SUBSTR(JOB.JOBNAME,1,25) "Jobname",'|',
  (SELECT SUBSTR(VAR.VAREXPR,1,15) 
FROM CTMSLO80.CMS_SETVAR VAR
    WHERE var.var = '%%PS8-PRCSNAME'
      AND JOB.jobno   =  VAR.jobno) "Process",'|',
  (SELECT SUBSTR(VAR.VAREXPR,1,30) FROM CTMSLO80.CMS_SETVAR VAR
    WHERE var.var = '%%PS8-RUNCONTROLID'
      AND JOB.jobno   =  VAR.jobno) "Run Cntrl ID",'|',
  NVL((SELECT SUBSTR(VAR.VAREXPR,1,20) FROM CTMSLO80.CMS_SETVAR VAR
    WHERE var.var = '%%PS8-PRCSTYPE'
      AND JOB.jobno   =  VAR.jobno), ' ') "Process Type",'|',
  SUBSTR(DAYSCAL,1,10) "Calendar",'|',
  NVL2(JOB.FROMTIME,SUBSTR(JOB.FROMTIME,1,2)||':'||SUBSTR(JOB.FROMTIME,3,2),' ') "From",'|',
  NVL2(JOB.Until  ,SUBSTR(JOB.Until,1,2)||':'||SUBSTR(JOB.Until,3,2),' ') "Until",'|',
   Case
WHEN JOB.DAYSTR = 'ALL' THEN
JOB.DAYSTR
Else
SUBSTR(NVL(REPLACE(REPLACE(REPLACE(REPLACE(TRANSLATE(JOB.WDAYSTR,'01234567AL','0MTW4F7AL'),'0','Su'),'4','Th'),'7','Sa'),'ALL','Daily'),' '),1,16)
End
"Days",'|',
  NVL(JOB.DESCRIPT,' ') "Description",'|',
  SUBSTR (job.jobname,1,5) "Table",'|',
(SELECT SUBSTR (CON.CONDNAME,1,75) FROM CTMSLO80.CMS_CON_J CON
   WHERE CON.ROWTYPE = 'I' 
   AND JOB.JOBNO = CON.JOBNO) "In Cond",'|',
  (SELECT SUBSTR(VAR.VAREXPR,1,35) FROM CTMSLO80.CMS_SETVAR VAR
    WHERE var.var = '%%PS8-DESCRIPTION'
      AND JOB.jobno   =  VAR.jobno) "Description",'|',
  SUBSTR(JOB.OWNER,1,6) "BMCID",'|',
  NVL2(JOB.DESCRIPT,(SUBSTR(JOB.DESCRIPT,1,INSTR(JOB.DESCRIPT,'/',1,1)-1)),'1') JOBORDER
  FROM CTMSLO80.CMS_JOBDEF JOB, CTMSLO80.CMS_SETVAR VAR
      where  OWNER LIKE 'BMCHR'
      and JOB.JOBno   =  VAR.JOBno

我遇到麻烦的部分是:

(SELECT SUBSTR (CON.CONDNAME,1,75) FROM CTMSLO80.CMS_CON_J CON
   WHERE CON.ROWTYPE = 'I' 
   AND JOB.JOBNO = CON.JOBNO) "In Cond",'|',

它将返回一个值,但如果我有多个值要返回,则会出现错误" ORA-01427:单行子查询返回多行"

我尝试过各种方法,比如XML路径,IN,EXISTS等,但这些方法给了我不同的错误,我无法解决。任何人都有这样的经历吗?

===========================

感谢您的回复

版本,如果PL / SQL是9.0.6.1655

不知道你的意思是什么" Delimiter"

没有成功将代码分解为更小的块。我没有编写大部分代码,但我正在尝试调整它以适应我想要做的事情。

提供的链接确实有助于消除错误。我使用" MAX"功能并将相关查询更改为:

(SELECT max(SUBSTR (CON.CONDNAME,1,75)) FROM CTMSLO80.CMS_CON_J CON
   WHERE CON.ROWTYPE = 'I' 
   AND JOB.JOBNO = CON.JOBNO) "In Cond",'|',

现在它至少会返回第一个项目。但是,我希望能够返回多个项目。查询的这一部分返回一个具有如下值的列:

在Cond

示例1

还有更多的数据需要提取,我希望它能像这样返回:

在Cond

example1,example2

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

如果您需要列表,请使用LISTAGG()

(SELECT LISTAGG(SUBSTR(CON.CONDNAME, 1, 75), '|') WITHIN GROUP (ORDER BY CON.CONDNAME)
 FROM CTMSLO80.CMS_CON_J CON
 WHERE CON.ROWTYPE = 'I' AND JOB.JOBNO = CON.JOBNO
)  as "In Cond", 

请注意,列表的最大大小受字符串的Oracle限制,4,000个字符的限制。如果列表太长,您可能会溢出。