查询中的多个COUNT返回不正确的结果

时间:2013-12-16 18:07:49

标签: sql sqlite

我正在使用SQLite,而且我对SQL很新。我遇到一个查询问题,我的新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 个答案:

答案 0 :(得分: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