我正在使用ORACLE 11g DB,通过SQL Dev工具 无法使用带有“Distinct”子句的Collect函数。在我的程序中使用时,它无法识别!
我的查询参考:
SELECT nvl(spicd.company_code, '') companycode
, nvl(scc.company_description, '') companydesc
, nvl(spicd.plant_code, '') plantcode
, CAST(COLLECT(DISTINCT svh.haulier_code) AS varchar2_ntt) hauliercode
, CAST(COLLECT(DISTINCT sh.hauier_name) AS varchar2_ntt) hauliername
FROM saistb_company_code scc
, saistb_pve_indv_contact_det spicd
LEFT OUTER JOIN saistb_vendor_haulier svh
ON svh.company_code = spicd.company_code
AND svh.plant_code = spicd.plant_code
AND svh.vendor_code = spicd.vendor_code
LEFT OUTER JOIN saistb_haulier sh
ON sh.haulier_code = svh.haulier_code
WHERE scc.company_code = spicd.company_code
AND spicd.company_code LIKE <<companycode>>
AND spicd.plant_code LIKE <<plantcode>>
GROUP BY nvl(spicd.company_code, '')
, nvl(scc.company_description, '')
, nvl(spicd.plant_code, '')
此处varchar2_ntt
是:
create or replace TYPE varchar2_ntt AS TABLE OF VARCHAR2(4000);
返回的错误是:
Error(49,6): PL/SQL: ORA-30482: DISTINCT option not allowed for this function
答案 0 :(得分:1)
这是Oracle中一个老问题,其中SQL和PL / SQL引擎解析器不同,在这种情况下,PL / SQL不允许您在聚合函数中使用distinct
。请参阅2003年this AskTom对此的回应。
他的建议是使用动态打开的引用游标。其他解决方案是使用外部查询(如Glenn的答案)包装您的查询,或者,我的偏好,将其转换为视图并从中进行选择。使用动态SQL也适用于这种情况。
答案 1 :(得分:0)
如何将它包装在子查询中?
SELECT companyCode, companyDesc, plantCode,
cast(COLLECT(haulierCode) as varchar2_ntt) haulierCode,
cast(COLLECT(haulierName) as varchar2_ntt) haulierName
FROM (
SELECT
nvl(spicd.COMPANY_CODE,'') companyCode,
nvl(scc.COMPANY_DESCRIPTION,'') companyDesc,
nvl(spicd.PLANT_CODE,'') plantCode,
nvl(sh.HAULIER_CODE, 'UNKNOWN HAULIER CODE') haulierCode,
nvl(sh.haulier_name, 'UNKNOWN HAULIER NAME') haulierName
from
SAISTB_COMPANY_CODE scc,
SAISTB_PVE_INDV_CONTACT_DET spicd
left outer join SAISTB_VENDOR_HAULIER svh on
svh.COMPANY_CODE = spicd.COMPANY_CODE and
svh.PLANT_CODE = spicd.PLANT_CODE and
svh.VENDOR_CODE = spicd.VENDOR_CODE
left outer join SAISTB_HAULIER sh on
sh.HAULIER_CODE = svh.HAULIER_CODE
where
scc.COMPANY_CODE = spicd.COMPANY_CODE
and spicd.COMPANY_CODE like <<CompanyCode>>
and spicd.PLANT_CODE like <<PlantCode>>
group by
nvl(spicd.COMPANY_CODE,''),
nvl(scc.COMPANY_DESCRIPTION,''),
nvl(spicd.PLANT_CODE,''),
nvl(sh.HAULIER_CODE, 'UNKNOWN HAULIER CODE') haulierCode,
nvl(sh.haulier_name, 'UNKNOWN HAULIER NAME') haulierName
)
GROUP BY companyCode, companyDesc, plantCode
内部组执行“不同”操作。