ORA-01427:单行子查询返回多行,当使用SELECT COUNT时

时间:2014-07-01 09:44:03

标签: sql oracle select count ora-01427

我有这两个查询,两者都相同,但第一行的差异,第一个法则计算结果,另一个得到行, 问题是它得到行并且不能计算它们

第一个查询出错(ORA-01427:单行子查询返回多行)

第一个(计数行)

    SELECT  COUNT(*) FROM (
      SELECT A.* , 
      SUBSTR(A.RECORD_DATE,9,4) RECORD_NOTICE_TIME , 
      (SELECT B.CLOSE_FLAG FROM HARAM.NOTICES_DEPT B WHERE B.NOTICE_SN = A.NOTICE_SN AND B.DEPT_ID = 116 AND B.RECORD_STATUS <> 3) CLOSE_FLAG , 
      (SELECT DEPARTMENT_ID FROM HARAM.EMPLOYES WHERE PERSONAL_CODE =A.NOTICE_USER) NOTICE_USER_DEPT , 
      (SELECT SUBSTR(ND.CREATION_TIMESTAMP,9,4) TRANS_NOTICE_TIME FROM HARAM.NOTICES_DEPT ND WHERE ND.NOTICE_SN = A.NOTICE_SN AND ND.RECORD_STATUS != 3 AND ND.DEPT_ID = 116 ) TRANS_NOTICE_TIME,
      (SELECT  (SELECT DEPARTMENT_NAME FROM HARAM.DEPARTMENT WHERE DS.SECTION_ID=DEPARTMENT_ID) FROM HARAM.NOTICES_DEPT_SECTIONS DS WHERE DS.NOTICE_SN=A.NOTICE_SN) SECTION_NAME 
      FROM HARAM.NOTICES A 
      WHERE EXISTS (SELECT NULL FROM HARAM.NOTICES_DEPT C WHERE C.NOTICE_SN = A.NOTICE_SN AND C.RECORD_STATUS <> 3 AND C.DEPT_ID = 116 ) AND A.RECORD_STATUS <> 3 
    ) 
    WHERE NOTICE_STATUS != 5 AND RECORD_STATUS <> 3 AND CLOSE_FLAG=3 AND SECTION_NAME IS NOT NULL
    ORDER BY CLOSE_FLAG DESC , CREATION_TIMESTAMP DESC;

第二个(获取行)

    SELECT * FROM (
      SELECT A.* , 
      SUBSTR(A.RECORD_DATE,9,4) RECORD_NOTICE_TIME , 
      (SELECT B.CLOSE_FLAG FROM HARAM.NOTICES_DEPT B WHERE B.NOTICE_SN = A.NOTICE_SN AND B.DEPT_ID = 116 AND B.RECORD_STATUS <> 3) CLOSE_FLAG , 
      (SELECT DEPARTMENT_ID FROM HARAM.EMPLOYES WHERE PERSONAL_CODE =A.NOTICE_USER) NOTICE_USER_DEPT , 
      (SELECT SUBSTR(ND.CREATION_TIMESTAMP,9,4) TRANS_NOTICE_TIME FROM HARAM.NOTICES_DEPT ND WHERE ND.NOTICE_SN = A.NOTICE_SN AND ND.RECORD_STATUS != 3 AND ND.DEPT_ID = 116 ) TRANS_NOTICE_TIME, 
      (SELECT (SELECT DEPARTMENT_NAME FROM HARAM.DEPARTMENT WHERE DS.SECTION_ID=DEPARTMENT_ID) FROM HARAM.NOTICES_DEPT_SECTIONS DS WHERE DS.NOTICE_SN=A.NOTICE_SN) SECTION_NAME 
      FROM HARAM.NOTICES A  
      WHERE EXISTS (SELECT NULL FROM HARAM.NOTICES_DEPT C WHERE C.NOTICE_SN = A.NOTICE_SN AND C.RECORD_STATUS <> 3 AND C.DEPT_ID = 116 ) AND A.RECORD_STATUS <> 3 
    ) 
    WHERE NOTICE_STATUS != 5 AND RECORD_STATUS <> 3 AND CLOSE_FLAG=3 AND SECTION_NAME IS NOT NULL
    ORDER BY CLOSE_FLAG DESC,CREATION_TIMESTAMP DESC;

1 个答案:

答案 0 :(得分:1)

您可能需要将INNER选择替换为下面的一个。我将其转换为Join并使用ROWNUM < =1将行限制为最大值1。

(SELECT
  D.DEPARTMENT_NAME
FROM HARAM.NOTICES_DEPT_SECTIONS DS, HARAM.DEPARTMENT D
WHERE DS.NOTICE_SN=A.NOTICE_SN
 AND DS.SECTION_ID=D.DEPARTMENT_ID
 AND ROWNUM <= 1
) SECTION_NAME