2017-06-28 79 views
0

我正在嘗試計算2個子查詢的計數。但我得到以下錯誤。我分別執行了兩個子查詢,它工作正常。錯誤可能是因爲我嘗試將它們轉換爲單個查詢。有任何想法嗎?減去子查詢計數DB2

enter image description here

select 
(select count(*) FROM TESTEA.AIT_P_NUMBER where 
rtrim(ltrim(translate(PNU_POL,' ','1234567890'))) = '') 
- 
(select count(*) FROM TESTEA.AIT_P_NUMBER) 

回答

1

你能試着從DUAL選擇:

SELECT 
    (SELECT COUNT(*) FROM TESTEA.AIT_P_NUMBER 
    WHERE RTRIM(LTRIM(TRANSLATE(PNU_POL, ' ', '1234567890'))) = '') - 
    (SELECT COUNT(*) FROM TESTEA.AIT_P_NUMBER) 
FROM DUAL; 

其實,有可以使用包括有條件的聚合單查詢解決方法:

SELECT 
    SUM(CASE WHEN RTRIM(LTRIM(TRANSLATE(PNU_POL, ' ', '1234567890'))) = '' 
      THEN 1 ELSE 0 END) - COUNT(*) 
FROM TESTEA.AIT_P_NUMBER 
+0

它說 「DUAL」 是一個未定義的名稱。 SQLSTATE = 42704 –

+0

什麼是'PNU_POL',你確定這兩個子查詢都是單獨運行的嗎? –

+0

多數民衆贊成在字段名稱 - 是他們都成功運行... –

1

解決方案1 :

values (SELECT COUNT(*) FROM TESTEA.AIT_P_NUMBER where trim(translate(PNU_POL,'   ','1234567890')) = '') 
     - (SELECT COUNT(*) nb FROM TESTEA.AIT_P_NUMBER) 
+0

'VALUES'通常對僞造文件(如SYSIBM.SYSDUMMY1或DUAL)進行查詢更有意義。 – WarrenT

0

解決方案2:

SELECT sum(case when trim(translate(PNU_POL,'   ','1234567890')) = '' then 1 else 0 end) - count(*) 
FROM TESTEA.AIT_P_NUMBER 
0

解決方案3:

select (SELECT COUNT(*) FROM TESTEA.AIT_P_NUMBER where trim(translate(PNU_POL,' ','1234567890')) = '') 
     - (SELECT COUNT(*) nb FROM TESTEA.AIT_P_NUMBER) 
from SYSIBM.SYSDUMMY1 
0

解決方案4:

select sum(nb) from 
(         
    select count(*) nb          
    from TESTEA.AIT_P_NUMBER where trim(translate(PNU_POL,'   ','1234567890')) = ''  
    union all             
    select -count(*) nb          
    from TESTEA.AIT_P_NUMBER            
) nb