2013-12-16 177 views
1

我使用的是SQLite,而且我一般對SQL很陌生。我遇到了一個查詢問題,我的新COUNT語句不應該返回相同的數字。當我分別運行這兩個子查詢時,我得到了正確的結果,所以我知道我只是把它們混合在一起而已。任何關於如何使這個不那麼醜陋的建議也非常感謝!查詢中的多個COUNT返回不正確的結果

我用下面的非常難看的select語句:

SELECT BATCH_ID, PROGRAM_ID, 
    COUNT((SELECT ID FROM PARTS 
      WHERE DROPSHIP_ONLY = 'No' 
      AND OBSOLETE = 'No' 
      AND DISCONTINUED = 'No')) 
      AS 'Active Parts', 
    COUNT((SELECT ID FROM PARTS 
      WHERE DROPSHIP_ONLY = 'No' 
      AND OBSOLETE = 'No' 
      AND DISCONTINUED = 'No' 
      AND ON_HAND > 0 
      AND ON_HAND > SAMPLE_LEVEL)) 
      AS 'Instock Parts' 
      FROM PARTS 
      GROUP BY BATCH_ID, PROGRAM_ID; 

它返回:

BATCH_ID PROGRAM_ID Active Parts Instock Parts 
201311 Vendor1 1390   1390 
201311 Vendor2 1433   1433 
201311 Vendor3 213   213 
201311 Vendor4 3595   3595 
201311 Vendor5 98   98 
201311 Vendor6 3   3 

預期結果的活性部位是:

201311 Vendor1 1144 
201311 Vendor2 1380 
201311 Vendor3 100 
201311 Vendor4 2276 
201311 Vendor5 98 
201311 Vendor6 3 

的預期結果Instock Parts是:

201311 Vendor1 15 
201311 Vendor2 1272 
201311 Vendor3 45 
201311 Vendor4 1767 
201311 Vendor5 97 
201311 Vendor6 3 

感謝您的任何幫助或建議!

回答

1

嘗試它使用CASE()

SELECT BATCH_ID, 
     PROGRAM_ID, 
     SUM(CASE WHEN DROPSHIP_ONLY = 'No' 
         AND OBSOLETE = 'No' 
         AND DISCONTINUED = 'No' 
       THEN 1 END) AS 'Active Parts', 
     SUM(CASE WHEN DROPSHIP_ONLY = 'No' 
         AND OBSOLETE = 'No' 
         AND DISCONTINUED = 'No' 
         AND ON_HAND > 0 
         AND ON_HAND > SAMPLE_LEVEL 
       THEN 1 END) AS 'Instock Parts' 
FROM PARTS 
WHERE DROPSHIP_ONLY = 'No' 
     AND OBSOLETE = 'No' 
     AND 
     (
      (DISCONTINUED = 'No') 
      OR 
      (DISCONTINUED = 'No' 
      AND ON_HAND > 0 
      AND ON_HAND > SAMPLE_LEVEL) 
     ) 
GROUP BY BATCH_ID, PROGRAM_ID 
+0

神聖的人,這是快。它看起來正常工作!你能否在WHERE子句之後解釋嵌套AND,具體說明爲什麼當它已經在WHERE子句的開頭指定時,它需要嵌套在AND子句中的DROPSHIP_ONLY ='No'?非常感謝! – Methonis

+0

這是一個錯字。它應該是'DISCONTINUED ='不'。 –

+0

好的,謝謝澄清! – Methonis

相關問題