2017-05-26 75 views
0

我運行下面的查詢,試圖找到第一次插入行的重複實例的存在: -查詢返回ORA-00936:缺少表達

SELECT COUNT(*) 
    FROM rlx_service_info 
    WHERE row(personalaccountid,serviceid,serviceline, 
       userserviceid,servicerf) IN (SELECT personalaccountid, 
                serviceid, 
                serviceline, 
                userserviceid, 
                servicerf 
              FROM rlx_service_info 
              WHERE masteraccountid = 'x' 
               AND status   = 30 
               AND rownum   =1 
              ORDER BY startdate); 
+0

使用行()在Oracle中無效。 –

+0

@NicholasKrasnov難怪我無法找到文檔... –

回答

0

您可以使用分析功能(無需第二個表掃描)的所有重複的行:

SELECT * 
FROM (
    SELECT r.*, 
     ROW_NUMBER() 
      OVER (
      PARTITION BY personalaccountid, 
          serviceid, 
          serviceline, 
          userserviceid, 
          servicerf 
      ORDER BY  startdate 
      ) as rn, 
     COUNT(CASE WHEN masteraccountid = 'x' AND status = 30 THEN 1 END) 
      OVER (
      PARTITION BY personalaccountid, 
          serviceid, 
          serviceline, 
          userserviceid, 
          servicerf 
      ) as ct 
    FROM rlx_service_info r 
) 
WHERE ct > 0 
AND rn > 1; 

如果你只是想的計數,然後將外部查詢更改爲:

SELECT COUNT(*) 
FROM (
    SELECT COUNT(CASE WHEN masteraccountid = 'x' AND status = 30 THEN 1 END) 
      OVER (
      PARTITION BY personalaccountid, 
          serviceid, 
          serviceline, 
          userserviceid, 
          servicerf 
      ) as ct 
    FROM rlx_service_info r 
) 
WHERE ct > 0; 
2

要解決的語法,你必須刪除roworder by條款。 此外,如果子查詢只給一個行(rownum = 1)你不需要一個IN

SELECT COUNT(*) 
    FROM rlx_service_info 
WHERE (personalaccountid, 
     serviceid, 
     serviceline, 
     userserviceid, 
     servicerf) = ( SELECT personalaccountid, 
           serviceid, 
           serviceline, 
           userserviceid, 
           servicerf 
          FROM rlx_service_info 
          WHERE  masteraccountid = 'x' 
           AND status = 30 
           AND ROWNUM = 1) 

例如:

SQL> select 1 
    2 from dual 
    3 where (1, 2) in (select 1, 2 from dual); 

     1 
---------- 
     1 

SQL> select 1 
    2 from dual 
    3 where row(1, 2) in (select 1, 2 from dual); 
where row(1, 2) in (select 1, 2 from dual) 
       * 
ERROR at line 3: 
ORA-00936: missing expression 

但是,如果你需要的子查詢只返回一行與最低startDate,認爲order by結合rownum條件不是一種方式;你會發現許多關於如何做到這一點的好答案。

例如:

SQL> select * 
    2 from (
    3   select 1 x from dual union all 
    4   select 2 x from dual 
    5  ) 
    6 where rownum = 1 
    7 order by x; 

     X 
---------- 
     1 

SQL> select * 
    2 from (
    3   select 2 x from dual union all 
    4   select 1 x from dual 
    5  ) 
    6 where rownum = 1 
    7 order by x; 

     X 
---------- 
     2 
+0

它說ORA-00920:在最後一行無效的關係運算符,無法弄清楚爲什麼 –

+0

@SohamBanerjee刪除'order by'子句 - 不允許在該子查詢中。坦率地說,它在那裏沒有意義。 –

+0

剛剛編輯,以更好地解釋 – Aleksej